Flutter Tip: Estimating Text Color Based on Background Color

Flutter Tip: Estimating Text Color Based on Background Color

Have you ever wanted to set the color of your text to a dynamic background color (or vice versa)? Whilst there are many ways to do this, a quick and easy method is the use of ThemeData.estimateBrightnessForColor(Color color).

We can use this to determine which color our Textelement should be depending on our background color.

import 'dart:math';
import 'package:flutter/material.dart';

class ColorEstimationPage extends StatelessWidget {
  Color _randomBackgroundColor() {
    List<Color> colors = [Colors.red, Colors.green, Colors.amber, Colors.black];

    return colors[Random().nextInt(colors.length)];
  }

  Color _textColorForBackground(Color backgroundColor) {
    if (ThemeData.estimateBrightnessForColor(backgroundColor) ==
        Brightness.dark) {
      return Colors.white;
    }

    return Colors.black;
  }

  @override
  Widget build(BuildContext context) {
    Color bgColor = _randomBackgroundColor();
    return Scaffold(
      backgroundColor: bgColor,
      body: Center(
        child: Text(
          "I'm the correct text color!",
          style: TextStyle(color: _textColorForBackground(bgColor)),
        ),
      ),
    );
  }
}

Here's an example of how this looks for a few of the colors: