Looking for a way to save some simple data in your Flutter app? The Shared Preferences package is the answer. It is a wrapper for platform specific storage systems: SharedPreferences on Android, NSUserDefaults on iOS, and Local Storage on the web. The key value store supports String, int, bool, double, and List<String>. It is extremely easy to implement and should only be used for simple data like app settings or user tokens etc. For more complex data structures you should look at other solutions.
To show you how Shared Preferences are working I wrote some code for a small sample app.
import 'package:flutter/material.dart';
void main() => runApp(App());
class App extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: HomePage(),
);
}
}
class HomePage extends StatefulWidget {
const HomePage({Key key}) : super(key: key);
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
bool _switchValue1 = true;
bool _switchValue2 = true;
bool _switchValue3 = true;
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Switch(
value: _switchValue1,
onChanged: (bool value) {
setState(() => _switchValue1 = value);
},
),
Switch(
value: _switchValue2,
onChanged: (bool value) {
setState(() => _switchValue2 = value);
},
),
Switch(
value: _switchValue3,
onChanged: (bool value) {
setState(() => _switchValue3 = value);
},
)
],
)),
);
}
}
The default route of our MaterialApp is a StatefulWidget called Homepage. It has three _switchValue variables which are used as the value for the corresponding Switch widgets in the layout. With the onChanged method the variables update every time the switch is toggled.
You can start the app and toggle the switches but once you close the values are lost. To save the data we need to add the Shared Preferences package.
We start with adding the SharedPreferences package to the pubspec.yaml file and running flutter pub get.
name: howtosharedpref
description: A sample project.
publish_to: 'none'
version: 1.0.0+1
environment:
sdk: ">=2.7.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
shared_preferences:
dev_dependencies:
flutter_test:
sdk: flutter
flutter:
uses-material-design: true
import 'package:shared_preferences/shared_preferences.dart';
Once that is done, we can update the code in our main.dart file. We add two methods to the _HomePageState class. One will load the data when we start the app the other one is saving the data every time the values change.
void loadPref() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
_switchValue1 = prefs.getBool('switch1') ?? true;
_switchValue2 = prefs.getBool('switch2') ?? true;
_switchValue3 = prefs.getBool('switch3') ?? true;
});
}
void savePref() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
await prefs.setBool('switch1', _switchValue1);
await prefs.setBool('switch2', _switchValue2);
await prefs.setBool('switch3', _switchValue3);
}
Before we can get or set any values, we first need to load the Shared Preferences with the getInstance method. Then we can get the bool values for our switches with the getBool method that needs a String name to find the right data. To write the values to disk we use the setBool method.
To have the data load when the app starts we add a initState override to _HomePageState.
@override
void initState() {
super.initState();
loadPref();
}
Finally to save everytime the switches are toggled we add savePref() to the onChanged methods.
onChanged: (bool value) {
savePref();
setState(() => _switchValue1 = value);
}
The Shared Preferences object has two more methods that could be useful. With remove we can delete a single key/value pair and with clear we can delete all our data.
await prefs.remove('value name');
await prefs.clear();