flutterdartmaterial3themedata

Flutter ColorScheme CopyWith brightness not working


In my Flutter project app_theme.dart file I have this code:

class AppTheme {
  static const primaryColor = Color.fromARGB(255, 106, 49, 185);

  static ThemeData lightTheme() {
    return ThemeData(
      useMaterial3: true,
      colorScheme: ColorScheme.fromSeed(
        seedColor: primaryColor,
        brightness: Brightness.light,
      ),
    );
  }

  static ThemeData darkTheme() {
    return ThemeData(
      useMaterial3: true,
      colorScheme: ColorScheme.fromSeed(
        seedColor: primaryColor,
        brightness: Brightness.dark,
      ),
    );
  }

Then in main.dart, my Material App widget implements this like so:

theme: AppTheme.lightTheme(),
darkTheme: AppTheme.darkTheme(),

This works correctly, so that in the Android emulator, when I switch between dark and light mode (within settings), the app automatically changes.

But what I wanted to do was declare the ColorScheme separately (so I can override certain colors etc) and then just use copyWith to declare the brightness in the ThemeData:

class AppTheme {
  static const primaryColor = Color.fromARGB(255, 106, 49, 185);

  static ColorScheme colorScheme = ColorScheme.fromSeed(
    seedColor: primaryColor,
    // Customisation goes here
  );

  static ThemeData lightTheme() {
    return ThemeData(
      useMaterial3: true,
      colorScheme: colorScheme.copyWith(
        brightness: Brightness.light,
      ),
    );
  }

  static ThemeData darkTheme() {
    return ThemeData(
      useMaterial3: true,
      colorScheme: colorScheme.copyWith(
        brightness: Brightness.dark,
      ),
    );
  }

But this does not work. It just stays in light mode all the time, although no errors are thrown.

Any ideas what I'm doing wrong?


Solution

  • ColorScheme.fromSeed constructor generates a ColorScheme derived from the given seedColor. Copying the generated object obviously does not generate colours again. Something like this would work:

    class AppTheme {
      static const primaryColor = Color.fromARGB(255, 106, 49, 185);
    
      static ColorScheme fromBrightness({required Brightness brightness}) {
        return ColorScheme.fromSeed(
          brightness: brightness,
          seedColor: primaryColor,
          // Customisation goes here
        );
      }
    
      static ThemeData lightTheme() {
        return ThemeData(
          useMaterial3: true,
          colorScheme: AppTheme.fromBrightness(
            brightness: Brightness.light,
          ),
        );
      }
    
      static ThemeData darkTheme() {
        return ThemeData(
          useMaterial3: true,
          colorScheme: AppTheme.fromBrightness(
            brightness: Brightness.dark,
          ),
        );
      }
    }