Updated 3 December 2024
ColorFilter
is a class in Flutter that allows you to apply color transformations to widgets, images, and other visual elements. It is part of the flutter/painting.dart
package and provides a way to modify the colors of visual content by applying a variety of effects such as grayscale, sepia, inversion, and more. This is typically used in combination with widgets like ColorFiltered
or ImageFiltered
to apply the desired effect to a specific child widget.
ColorFilter
widget In Flutter :The ColorFiltered
widget provides a simple and declarative way to apply color filters, such as tints, saturation adjustments, or custom color overlays to widgets like images, icons, and text.
With ColorFiltered
, you can use predefined color filters like ColorFilter.mode()
or create custom ColorFilter
instances that apply complex transformations
You can use ColorFiltered
to create visually interesting effects for UI elements, such as adding a subtle tint to an image or applying a color overlay for design consistency.
You can use ColorFiltered
to adjust elements according to the app’s theme, making it easier to change colors dynamically without rewriting large parts of your widget tree.
First we need to create a new Flutter project and add the assets path for your images in the pubspec.yaml file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
name: flutter_color_filter_example description: A new Flutter project. # Flutter SDK version environment: sdk: '>=3.0.0 <4.0.0' dependencies: flutter: sdk: flutter dev_dependencies: flutter_test: sdk: flutter # Add the assets you want to use flutter: assets: - assets/images/ # Define your asset paths here |
This is the pubspec.yaml
configuration for a Flutter project that uses assets. It specifies the minimum Flutter SDK version as 3.0.0 and includes the flutter_test
dependency for testing. The flutter
section defines the assets to be used in the project, specifically all images in the assets/images/
directory.
Now, run the command “flutter pub get”, this command will Add the assets folder path to your flutter project.
Ensure you have the directories defined in pubspec.yaml for your assets, such as assets/images. You can create these folders manually in your project directory and place your image assets inside.
Now, you can access your images using the assets folder .
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 |
import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { static final String title = ' Filter Example'; @override Widget build(BuildContext context) => MaterialApp( debugShowCheckedModeBanner: false, title: title, theme: ThemeData(primarySwatch: Colors.red), home: FilterPage(), ); } class FilterPage extends StatefulWidget { @override _FilterPageState createState() => _FilterPageState(); } class _FilterPageState extends State<FilterPage> { final String imagePath = 'assets/images/image.jpg'; final List<String> filters = ['Normal', 'Sepia', 'Grayscale', 'Invert']; int selectedFilterIndex = 0; @override Widget build(BuildContext context) => Scaffold( appBar: AppBar( title: Text('Filters view'), ), body: Column( children: [ Expanded( child: Center( child: applyFilter(selectedFilterIndex), ), ), Container( height: 120, padding: const EdgeInsets.symmetric(vertical: 10), child: ListView.builder( scrollDirection: Axis.horizontal, itemCount: filters.length, itemBuilder: (context, index) => GestureDetector( onTap: () => setState(() => selectedFilterIndex = index), child: Column( children: [ Container( margin: const EdgeInsets.symmetric(horizontal: 10), width: 70, height: 70, decoration: BoxDecoration( border: Border.all( color: selectedFilterIndex == index ? Colors.red : Colors.transparent, width: 3, ), borderRadius: BorderRadius.circular(10), ), child: ClipRRect( borderRadius: BorderRadius.circular(10), child: applyFilter(index, isThumbnail: true), ), ), const SizedBox(height: 5), Text( filters[index], style: TextStyle( fontSize: 14, color: selectedFilterIndex == index ? Colors.red : Colors.black, ), ), ], ), ), ), ), ], ), ); Widget applyFilter(int filterIndex, {bool isThumbnail = false}) { switch (filterIndex) { case 1: // Sepia return ColorFiltered( colorFilter: ColorFilter.mode( Colors.brown.withOpacity(0.5), BlendMode.modulate, ), child: Image.asset(imagePath, fit: BoxFit.cover), ); case 2: // Grayscale return ColorFiltered( colorFilter: const ColorFilter.matrix([ 0.2126, 0.7152, 0.0722, 0, 0, // R 0.2126, 0.7152, 0.0722, 0, 0, // G 0.2126, 0.7152, 0.0722, 0, 0, // B 0, 0, 0, 1, 0, // Alpha ]), child: Image.asset(imagePath, fit: BoxFit.cover), ); case 3: // Invert return ColorFiltered( colorFilter: const ColorFilter.matrix([ -1, 0, 0, 0, 255, // R 0, -1, 0, 0, 255, // G 0, 0, -1, 0, 255, // B 0, 0, 0, 1, 0, // Alpha ]), child: Image.asset(imagePath, fit: BoxFit.cover), ); default: // Normal return Image.asset( imagePath, fit: isThumbnail ? BoxFit.cover : BoxFit.contain, ); } } } |
In this Flutter app code allows users to apply different color filters (Normal, Sepia, Grayscale, Invert) to an image. The main screen displays the image with the selected filter applied using the ColorFiltered
widget, and a horizontal list of filter options is provided at the bottom. When a user taps a filter, the image is updated to show the selected effect. The applyFilter
method uses a switch
statement to handle each filter type, applying specific color transformations using ColorFilter
. Additionally, each filter has a small thumbnail preview, and the app dynamically updates the UI using a StatefulWidget
to reflect the user’s selection.
The ColorFiltered
class in Flutter provides an easy way to apply color transformations to widgets, enabling effects like tinting, brightness adjustment, and custom overlays. It simplifies the creation of dynamic, visually appealing UI elements without complex styling or shaders. However, it’s important to use ColorFiltered
judiciously, as excessive usage may affect performance, particularly with intricate UI structures or high-resolution images. Always evaluate the design and performance impact when using it to ensure a balance between aesthetics and efficiency.
Hope you enjoyed this article. For more updates, make sure to keep following Mobikul Blogs to learn more about mobile app development
Other blogs you may like…
Dart Macros: Metaprogramming with Code Generation
How To Use InAppWebView In Flutter
Utilizing Flutter Gen to Enhance Flutter Development
Integrating Gemini with Flutter
Thanks for reading this blog ❤️
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.