I want to change text (and Icon) colors based on the background image for visibility.
I've tried: Using palette_generator package, to check the Dominant Color of the background Image and useWhiteForgroundForColor function (returns a bool) from flutter_statusbarcolor package to select black or white color for the my text (and Icon) colors.
The Problem: Sometimes dominant color turns out null. In my tests, this happens with black and white colors and I don't know of any ways to find out which one.
Future<bool> useWhiteTextColor(String imageUrl) async {
PaletteGenerator paletteGenerator =
await PaletteGenerator.fromImageProvider(
NetworkImage(imageUrl),
// Images are square
size: Size(300, 300),
// I want the dominant color of the top left section of the image
region: Offset.zero & Size(40, 40),
);
Color dominantColor = paletteGenerator.dominantColor?.color;
// Here's the problem
// Sometimes dominantColor returns null
// With black and white background colors in my tests
if (dominantColor == null) print('Dominant Color null');
return useWhiteForeground(dominantColor);
}
I found other methods for other languages, but I don't know a way to implement the same method in dart.
Additional note: My actual code includes some additional complications. I am using a SliverAppBar and here I want to determine the title and icons colors for when the flexibleSpace is expanded. I change their colors when collapsed with the help of the community based on this.
Steps. Step 1: Locate the file where you have placed the Text widget. Step 2: Inside the Text widget, add the Style parameter and assign the TextStyle widget. Step 3: Inside the TextStyle widget, add the color parameter and set the color of your choice.
Steps to set the background image:Step 1: Add the Container widget. Step 2: Add the decoration parameter (inside Container) and assign the BoxDecoration class. Step 3: Add the image parameter (inside BoxDecoration) and assign the DecorationImage class.
the color class already has a method to calculate luminance, called computeLuminance()
Color textColor = color.computeLuminance() > 0.5 ? Colors.black : Colors.white;
i use the below method to find out which one to be used (either black or white).
Color getTextColor(Color color) {
int d = 0;
// Counting the perceptive luminance - human eye favors green color...
double luminance =
(0.299 * color.red + 0.587 * color.green + 0.114 * color.blue) / 255;
if (luminance > 0.5)
d = 0; // bright colors - black font
else
d = 255; // dark colors - white font
return Color.fromARGB(color.alpha, d, d, d); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With