Home > other >  Shared ThemeData between light and dark themes
Shared ThemeData between light and dark themes

Time:02-15

I'm trying to avoid repeating my code.

My app has light and dark theme modes, and I'm trying to change my app theme in both modes without repeating lines, like the following code.

return MaterialApp(

  theme: ThemeData(
    primarySwatch: Colors.blue,
    // shared ThemeData between light and dark themes :(
    appBarTheme: const AppBarTheme(
      toolbarHeight: 100,
    ),
  ),

  darkTheme: ThemeData(
    brightness: Brightness.dark,
    // shared ThemeData between light and dark themes :(
    appBarTheme: const AppBarTheme(
      toolbarHeight: 100,
    ),
  ),

  themeMode: ThemeMode.dark,
);

As I explained in my code, that there are few lines repeated in both light and dark themedata

// shared ThemeData between light and dark themes :(
appBarTheme: const AppBarTheme(
  toolbarHeight: 100,
),

Is there a good and TESTED way to avoid this mistake?

CodePudding user response:

First define your ThemeData as a variable, for example:

final myTheme = ThemeData(
  // brightness: Brightness.light,
  primarySwatch: Colors.red,
  primaryColor: Colors.blue,
  cardColor: Color(0xCCF2F2F2),
);

You can then use your variable. If you want to modify a few items, you can use the copyWith constructor. For example:

MaterialApp(
  // light theme: use the variable as is
  theme: themeData,
  // dark theme: need to modify a few things
  darkTheme: themeData.copyWith(
    brightness: Brightness.dark, // change brightness
  ),
  home: MyHomePage(),
)

CodePudding user response:

make a ThemeData variable and put all the shared properties then use copyWith when you want to change something like this:

ThemeData _themeData = ThemeData(
      primarySwatch: Colors.indigo,
      appBarTheme: AppBarTheme(
                color : Colors.deepOrange,
             ),
    );

then :

theme: _themeData.copyWith(
      brightness: Brightness.dark,
  ),
  darkTheme: _themeData.copyWith(
    brightness: Brightness.dark
  ),
  themeMode: ThemeMode.light,

you can also use ThemeData.from()

  • Related