Flutter Shared Preferences Example
This article helps you to use shared preferences in flutter applications to store data in local. Shared Preferences store the data in a key-value pair. We can also get data in a key-value pair. You can also check out flutter storage related articles.
We can save large and complex data in local with the help of sqlite database but if we want to save small amount of data then we should use shared preferences instead of sqlite database. In SharedPreferences, we have to give just key for every single value so we can get that value using this same key.
In this example, We store and display some values with the help of shared preferences. We store user information at login screen. After submit button click, we display user information in profile screen. Now every time user opens app, we display profile page instead of login page because user already logged in.
Add below dependency in your pubspec file
Store Values in Shared Preferences
You can store values in shared preferences in the form of string, integer, boolean, double and list of strings.
SharedPreferences myPrefs = await SharedPreferences.getInstance();
myPrefs.setString(key, value);
}
SharedPreferences myPrefs = await SharedPreferences.getInstance();
myPrefs.setInt(key, value);
}
SharedPreferences myPrefs = await SharedPreferences.getInstance();
myPrefs.setBool(key, value);
}
SharedPreferences myPrefs = await SharedPreferences.getInstance();
myPrefs.setDouble(key, value);
}
SharedPreferences myPrefs = await SharedPreferences.getInstance();
myPrefs.setStringList(key, value);
}
Retrieve Values From Shared Preferences
SharedPreferences myPrefs = await SharedPreferences.getInstance();
return myPrefs.getString(key) ?? “”;
}
SharedPreferences myPrefs = await SharedPreferences.getInstance();
return myPrefs.getInt(key) ?? 0;
}
SharedPreferences myPrefs = await SharedPreferences.getInstance();
return myPrefs.getBool(key) ?? false;
}
SharedPreferences myPrefs = await SharedPreferences.getInstance();
return myPrefs.getDouble(key) ?? 0;
}
SharedPreferences myPrefs = await SharedPreferences.getInstance();
return myPrefs.getStringList(key);
}
Check Key is Stored or Not
SharedPreferences myPrefs = await SharedPreferences.getInstance();
return myPrefs.containsKey(key);
}
Remove Specific Value
SharedPreferences myPrefs = await SharedPreferences.getInstance();
return myPrefs.remove(key);
}
Remove All Data From Shared Preferences
SharedPreferences myPrefs = await SharedPreferences.getInstance();
return myPrefs.clear();
}
Final Code
my_shared_preferences.dart
import 'package:shared_preferences/shared_preferences.dart'; class MySharedPreferences { MySharedPreferences._privateConstructor(); static final MySharedPreferences instance = MySharedPreferences._privateConstructor(); setStringValue(String key, String value) async { SharedPreferences myPrefs = await SharedPreferences.getInstance(); myPrefs.setString(key, value); } Future<String> getStringValue(String key) async { SharedPreferences myPrefs = await SharedPreferences.getInstance(); return myPrefs.getString(key) ?? ""; } setIntegerValue(String key, int value) async { SharedPreferences myPrefs = await SharedPreferences.getInstance(); myPrefs.setInt(key, value); } Future<int> getIntegerValue(String key) async { SharedPreferences myPrefs = await SharedPreferences.getInstance(); return myPrefs.getInt(key) ?? 0; } setBooleanValue(String key, bool value) async { SharedPreferences myPrefs = await SharedPreferences.getInstance(); myPrefs.setBool(key, value); } Future<bool> getBooleanValue(String key) async { SharedPreferences myPrefs = await SharedPreferences.getInstance(); return myPrefs.getBool(key) ?? false; } Future<bool> containsKey(String key) async { SharedPreferences myPrefs = await SharedPreferences.getInstance(); return myPrefs.containsKey(key); } removeValue(String key) async { SharedPreferences myPrefs = await SharedPreferences.getInstance(); return myPrefs.remove(key); } removeAll() async{ SharedPreferences myPrefs = await SharedPreferences.getInstance(); return myPrefs.clear(); } }
main.dart
import 'package:flutter/material.dart'; import 'my_shared_preferences.dart'; import 'login.dart'; import 'profile.dart'; void main() { runApp(MyApp()); } class MyApp extends StatefulWidget { @override State<StatefulWidget> createState() { // TODO: implement createState return MyAppState(); } } class MyAppState extends State<MyApp> { // This widget is the root of your application. bool isLoggedIn = false; MyAppState() { MySharedPreferences.instance .getBooleanValue("loggedin") .then((value) => setState(() { isLoggedIn = value; })); } @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, title: 'Flutter Demo', home: isLoggedIn ? Profile() : Login()); } }
login.dart
import 'package:flutter/material.dart'; import 'my_shared_preferences.dart'; import 'profile.dart'; class Login extends StatefulWidget { @override State<StatefulWidget> createState() { // TODO: implement createState return LoginState(); } } class LoginState extends State<Login> { TextEditingController controllerEmail = new TextEditingController(); TextEditingController controllerUserName = new TextEditingController(); TextEditingController controllerPassword = new TextEditingController(); @override Widget build(BuildContext context) { final formKey = GlobalKey<FormState>(); // TODO: implement build return SafeArea( child: Scaffold( body: SingleChildScrollView( child: Container( margin: EdgeInsets.all(25), child: Form( key: formKey, autovalidate: false, child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Row( mainAxisAlignment: MainAxisAlignment.start, children: <Widget>[ Text("Email Id:", style: TextStyle(fontSize: 18)), SizedBox(width: 20), Expanded( child: TextFormField( controller: controllerEmail, decoration: InputDecoration( hintText: "Please enter email", ), keyboardType: TextInputType.emailAddress, validator: (value) { if (value.trim().isEmpty) { return "Email Id is Required"; } }, ), ) ], ), SizedBox(height: 60), Row( mainAxisAlignment: MainAxisAlignment.start, children: <Widget>[ Text("UserName:", style: TextStyle(fontSize: 18)), SizedBox(width: 20), Expanded( child: TextFormField( decoration: InputDecoration( hintText: "Please enter username", ), validator: (value) { if (value.trim().isEmpty) { return "UserName is Required"; } }, controller: controllerUserName), ) ], ), SizedBox(height: 60), Row( mainAxisAlignment: MainAxisAlignment.start, children: <Widget>[ Text("Password:", style: TextStyle(fontSize: 18)), SizedBox(width: 20), Expanded( child: TextFormField( decoration: InputDecoration( hintText: "Please enter password", ), obscureText: true, validator: (value) { if (value.trim().isEmpty) { return "Password is Required"; } }, controller: controllerPassword), ) ], ), SizedBox(height: 100), SizedBox( width: 150, height: 50, child: RaisedButton( color: Colors.grey, child: Text("Submit", style: TextStyle(color: Colors.white, fontSize: 18)), onPressed: () { if(formKey.currentState.validate()) { var getEmail = controllerEmail.text; var getUserName = controllerUserName.text; var getPassword = controllerPassword.text; MySharedPreferences.instance .setStringValue("email", getEmail); MySharedPreferences.instance .setStringValue("username", getUserName); MySharedPreferences.instance .setStringValue("password", getPassword); MySharedPreferences.instance .setBooleanValue("loggedin", true); Navigator.pushReplacement( context, MaterialPageRoute(builder: (_) => Profile()), ); } }, ), ) ], ), ), ), )), ); } }
profile.dart
import 'package:flutter/material.dart'; import 'my_shared_preferences.dart'; import 'login.dart'; class Profile extends StatefulWidget { @override State<StatefulWidget> createState() { // TODO: implement createState return ProfileState(); } } class ProfileState extends State<Profile> { String email = ""; String username = ""; ProfileState() { MySharedPreferences.instance .getStringValue("email") .then((value) => setState(() { email = value; })); MySharedPreferences.instance .getStringValue("username") .then((value) => setState(() { username = value; })); } @override Widget build(BuildContext context) { // TODO: implement build return SafeArea( child: Scaffold( body: Center( child: Container( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text( "Hello, " + username, style: TextStyle(fontSize: 35, fontWeight: FontWeight.bold), ), SizedBox(height: 30), Text( email, style: TextStyle(fontSize: 25, fontWeight: FontWeight.bold), ), SizedBox(height: 80), SizedBox( width: 150, height: 50, child: RaisedButton( color: Colors.grey, child: Text("Logout", style: TextStyle(color: Colors.white, fontSize: 18)), onPressed: () { MySharedPreferences.instance.removeAll(); Navigator.pushReplacement(context, MaterialPageRoute(builder: (_) => Login())); }), ) ], ), ), ), ), ); } }




Pingback: Flutter Package for Utility Integration Tutorial - CodingWithDhrumil
Pingback: Hive Flutter Local Database Example - CodingWithDhrumil
Pingback: Image Picker Flutter Example - CodingWithDhrumil