Now a days, dark mode in apps have become very popular. Mostly all major apps give choice to users to switch to dark mode. Now let’s see how we can add this feature to our Flutter apps.
Flutter was build with theming, so dealing with OS level dark mode is pretty simple.
Transform your app idea into reality with our Flutter app development services.
If you check the MaterialApp
widget you will see we have the theme
and darkTheme
parameter where we can provide the dark ThemeData
in darkTheme
and light ThemeData
in theme
if we want our app to change the theme according to the system preferences.
1 2 3 4 5 |
MaterialApp( theme: ThemeData.light(), darkTheme: ThemeData.dark(), home: MyApp(), //Your home screen ) |
So here as mentioned in the widget we can set theme and darkTheme.
Below an example of main.dart representing the complete implementation:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
import 'package:flutter/material.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { final ValueNotifier<ThemeMode> _notifier = ValueNotifier(ThemeMode.light); @override Widget build(BuildContext context) { return ValueListenableBuilder<ThemeMode>( valueListenable: _notifier, builder: (_, mode, __) { return MaterialApp( theme: ThemeData.light(), darkTheme: ThemeData.dark(), themeMode: mode, // Decides which theme to show, light or dark. home: Scaffold( appBar: AppBar(title: Text("Home")), body: Center( child: ElevatedButton( onPressed: () => _notifier.value = mode == ThemeMode.light ? ThemeMode.dark : ThemeMode.light, child: Text('Toggle Theme'), ), ), ), ); }, ); } } |
Here, I have create a toggle button to switch theme mode using ValueNotifier.
Thanks for reading this article ❤
If I got something wrong 🙈, let me know in the comments. I would love to improve.