DEV Community

Jhin Lee
Jhin Lee

Posted on • Edited on

Build a flutter theme switcher with riverpod

With this article, I added dark and light themes in the MaterialApp.

Now it's time to add a toggle switch in the app. I'll use riverpod. One of the famous framework people uses for state management. As expressed in the official document, It's more caching framework itself, but It's helpful to cache the global states.

Setup the riverpod

  1. Add the riverpod package

    flutter pub add flutter_riverpod
    
  2. Wrap the MainApp with the ProviderScope
    From:

    void main() {
      runApp(const MyApp());
    }
    

    To:

    void main() {
      runApp(const ProviderScope(child: MyApp()));
    }
    

Implement the theme toggle switch

  1. Add the themeModeProvider

    final themeModeProvider = StateProvider<ThemeMode>((ref) {
      return ThemeMode.dark;
    });
    
  2. Convert the MyApp as ConsumerWidget and watch the provider

    class MyApp extends ConsumerWidget {
      const MyApp({super.key});
    
      @override
      Widget build(BuildContext context, WidgetRef ref) {
        final themMode = ref.watch(themeModeProvider);
        return MaterialApp(
          title: 'Flutter Demo',
          theme: ThemeData(
            useMaterial3: true,
            colorScheme: lightColorScheme,
            textTheme: textTheme,
          ),
          darkTheme: ThemeData(
            useMaterial3: true,
            colorScheme: darkColorScheme,
            textTheme: textTheme,
          ),
          themeMode: themMode, // Apply them theme
          home: const MyHomePage(title: 'Flutter Demo Home Page'),
        );
      }
    }
    

    Every time the themeModeProvider changes, the widget rebuilds and assigns the new value to the themeMode

    final themMode = ref.watch(themeModeProvider);
    
  3. Add the toggle button

    Consumer(builder: (context, ref, child) {
      final theme = ref.watch(themeModeProvider);
      return IconButton(
          onPressed: () {
            ref.read(themeModeProvider.notifier).state =
                theme == ThemeMode.light
                    ? ThemeMode.dark
                    : ThemeMode.light;
          },
          icon: Icon(theme == ThemeMode.dark
              ? Icons.light_mode
              : Icons.dark_mode));
    })
    

The complete code can be found on github

Top comments (0)