Flutter Dark and Light mode using Shared Preferences

Here is an example of how you can use the SharedPreferences package to store the user’s preferred mode (dark or light) in Flutter and apply it consistently throughout the app:

  1. First, add the SharedPreferences package to your pubspec.yaml file:


dependencies:
shared_preferences: ^0.7.3

 

  1. Next, create a top-level widget that will manage the app’s mode. This widget should have a stateful property called _darkMode that stores the current mode (true for dark mode, false for light mode). It should also have a method called _setDarkMode that updates the value of _darkMode and writes it to SharedPreferences.

import ‘package:flutter/material.dart’;
import ‘package:shared_preferences/shared_preferences.dart’;

class ModeProvider extends StatefulWidget {
final Widget child;

ModeProvider({@required this.child});

@override
_ModeProviderState createState() => _ModeProviderState();
}

class _ModeProviderState extends State<ModeProvider> {
bool _darkMode = false;

@override
void initState() {
super.initState();
_loadMode();
}

@override
Widget build(BuildContext context) {
return widget.child;
}

void _loadMode() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
_darkMode = prefs.getBool(‘darkMode’) ?? false;
});
}

void _setDarkMode(bool value) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
_darkMode = value;
});
prefs.setBool(‘darkMode’, value);
}
}

  1. Wrap your app’s root widget with the ModeProvider widget, and pass the mode down to child widgets as needed. For example:

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return ModeProvider(
child: MaterialApp(
theme: _darkMode ? ThemeData.dark() : ThemeData.light(),
home: HomePage(),
),
);
}
}

  • To update the mode from child widgets, you can use the Provider package to access the _setDarkMode method from the ModeProvider widget. For example:

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
final modeProvider = Provider.of(context);
return Scaffold(
appBar: AppBar(
title: Text(‘Home’),
),
body: Center(
child: FlatButton(
onPressed: () {
modeProvider._setDarkMode(!modeProvider._darkMode);
},
child: Text(‘Toggle mode’),
),
),
);

Content Protection by DMCA.com
Spread the love

Leave a Comment