You've successfully subscribed to
Great! Next, complete checkout for full access to
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.
Success! Your billing info is updated.
Billing info update failed.

Flutter Tip: Estimating Text Color Based on Background Color

Paul Halliday
Paul Halliday

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.amber,];

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

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


  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:


Paul Halliday

πŸ‘‹ Want to see more content? Head over to the YouTube channel:!