fluttermaterial-uimaterial-design

Best way to handle colors in Flutter for future dark/light theme support


I’m working on a Flutter project where colors are currently referenced in different ways. For example:

// Example 1:
style: TextStyle(
  fontSize: 20,
  color: _noAccountsExist
      ? const Color.fromARGB(255, 184, 184, 184)
      : const Color.fromARGB(255, 236, 236, 236),
  fontWeight: FontWeight.bold,
),

// Example 2
style: const TextStyle(color: Colors.black),

This works fine now, but our team plans to support light and dark themes in the future. I’d like to refactor the code so that colors are reusable and follow the Material theme system, rather than hardcoding Color.fromARGB or directly using Colors.black.

What is the recommended best practice for managing colors in a Flutter project so that we don't reuse the colors ?


Solution

  • Best Practice for Colors in Flutter

    Example

    theme.dart

    
    class AppTheme {
      static ThemeData light = ThemeData(
        colorScheme: const ColorScheme.light(
          primary: Colors.blue,
          onBackground: Colors.black,
        ),
      );
    
      static ThemeData dark = ThemeData(
        colorScheme: const ColorScheme.dark(
          primary: Colors.blueGrey,
          onBackground: Colors.white,
        ),
      );
    }
    
    

    main.dart

    MaterialApp(
      theme: AppTheme.light,
      darkTheme: AppTheme.dark,
      themeMode: ThemeMode.system,
    );
    

    Usage

    Text(
      "Hello",
      style: TextStyle(color: Theme.of(context).colorScheme.onBackground),
    );