0

How to manually set dark mode in flutter using ThemeData in Flutter?

I am currently using ThemeData to handle my darkMode events:

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'App',
      themeMode: ThemeMode.system,
      theme: MainTheme.light,
      darkTheme: MainTheme.dark,
      home: HomeScreen(),
      debugShowCheckedModeBanner: false,
    );
  }
}

I wanted to know, how to turn on dark mode manually in Flutter when I see a specific widget? In every Widget I make, I use this code to create a variable that checks if dark mode is activated or not so I can manually manage the colors:

var brightness = MediaQuery.of(context).platformBrightness;
darkModeOn = brightness == Brightness.dark;
Hamza Amr
  • 165
  • 1
  • 12

2 Answers2

1

The easiest method I have found to toggle between light and dark mode is with the adaptive theme package. https://pub.dev/packages/adaptive_theme

You need to wrap your MaterialApp with AdaptiveTheme in order to apply themes.

After that you can use this piece of code to toggle between light and dark mode: AdaptiveTheme.of(context).toggleThemeMode();

taco-tuesday
  • 56
  • 1
  • 5
0

One other way to have custom colors in dark and bright mode is to read the phone mode, then have if condition in constants.dart to switch between colors in 2 modes.