If you have a relatively small collection of key-values that you’d like to save, you should use the SharedPreferences Plugin. A SharedPreferences
object points to a file containing key-value pairs and provides simple methods to read and write them.
Flutter Shared preferences plugin Wraps NSUserDefaults (on iOS) and SharedPreferences (on Android), providing a persistent store for simple data. Data is persisted to disk automatically and asynchronously.
To use this plugin, add shared_preferences
as a dependency in your pubspec.yaml
file.
1.Add this to your package’s pubspec.yaml file:
dependencies: shared_preferences: "^0.2.4+1"
2. You can install packages from editor ‘packages get’
3. Import it
import 'package:shared_preferences/shared_preferences.dart';
Write to Shared Preferences
To write to a shared preferences file, create a SharedPreferences
by calling getInstance
on your SharedPreferences. Pass the keys and values you want to write with methods such as setInt()
and setString()
.For example:
_saveValues() async { SharedPreferences prefs = await SharedPreferences.getInstance(); prefs.setString("name", nameController.text); prefs.setString("phone", phoneController.text); }
Read from Shared Preferences
To retrieve values from a shared preferences file, call methods such as getInt()
and getString()
, providing the key for the value you want, and optionally a default value to return if the key isn’t present. For example:
getSharedPreferences() async { SharedPreferences prefs = await SharedPreferences.getInstance(); nameController.text = prefs.getString("name"); phoneController.text = prefs.getString("phone"); }