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.
the color class already has a method to calculate luminance, called computeLuminance()
Color textColor = color.computeLuminance() > 0.5 ? Colors.black : Colors.white;