bestTextColor function

Color bestTextColor(
  1. Color background, {
  2. List<Color> candidates = const [Colors.black, Colors.white],
  3. bool hasDarkBackground = true,
})

Picks the candidate color with the highest contrast against background.

If candidates is empty, this returns Colors.black by default.

Implementation

Color bestTextColor(
  Color background, {
  List<Color> candidates = const [Colors.black, Colors.white],
  bool hasDarkBackground = true,
}) {
  if (candidates.isEmpty) return Colors.black;

  Color best = candidates.first;
  var bestRatio = -1.0;
  for (final candidate in candidates) {
    final ratio = contrastRatio(
      candidate,
      background,
      hasDarkBackground: hasDarkBackground,
    );
    if (ratio > bestRatio) {
      best = candidate;
      bestRatio = ratio;
    }
  }
  return best;
}