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:
- First, add the SharedPreferences package to your pubspec.yaml file:
dependencies:
shared_preferences: ^0.7.3
- 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);
}
}
- 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 theModeProvider
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’),
),
),
);
I am passionate about learning and teaching new technology. Here You will get all information about Flutter, Laravel and New Technologies.