In this article, we will learn how to implement dark mode in our app without using any dark mode packages. In this article, I’m using a fresh new flutter app and will implement a dark mode inside it with a switch inside the drawer of the app. The button will provide system, light and dark mode options as shown in the gif above.

Without wasting any time let's jump to the steps.

Step 1: Add shared_preferences to your pubspec.yaml. We need this package to keep track of the user-preferred theme mode.

Step 2: Create a directory named sharedPreferences in lib and create a dart file inside it named app_theme_shared_preferences.dart as shown in the image below:

Step 4: Now add the below code inside app_theme_shared_preferences.dart like this (Not explaining code as it is pretty self explanatory):

Step 5: Now modify your main() method like this:

Step 5: In your MaterialApp() assign savedThemeMode to themeMode and ThemeData.dark() to darkTheme like this:

Step 5: Now convert MyApp to StatefulWidget from StatelessWidget.

Step 6: Create a themeMode variable inside the state of MyApp and assign it to themeMode in MaterialApp() like this:

Step 6: Now modify the MyApp() and home widget(MyHomePage() in this case) like this:

Step 6: Now in this example, I will be changing the themeMode through the drawer but you can do it anywhere you like. So create a file named drawer.dart and copy the following code inside it:

Step 6: Now the final step, insert the drawer inside your scaffold like this:

Result:

Your dark mode is all set now. To play with the demo app, just clone this always up-to-date repository.

Thanks for reading this article.

--

--