useWhiteForeground function

bool useWhiteForeground(
  1. Color backgroundColor, {
  2. double bias = 0.0,
})

Whether white text is easier to read than black text on backgroundColor.

Estimates how bright the colour looks to the human eye, then returns true for dark colours. Raise bias to choose white text on lighter backgrounds too, or lower it to prefer black.

final textColour = useWhiteForeground(bg) ? Colors.white : Colors.black;

Implementation

bool useWhiteForeground(Color backgroundColor, {double bias = 0.0}) {
  final int v = math
      .sqrt(
        math.pow(backgroundColor.redInt, 2) * 0.299 +
            math.pow(backgroundColor.greenInt, 2) * 0.587 +
            math.pow(backgroundColor.blueInt, 2) * 0.114,
      )
      .round();
  return v < 130 + bias ? true : false;
}