Hello friends, In today’s tutorial we would learn about Shared Preferences in flutter. Many of us don’t know about Shared Preferences, How it works, What it does and where can we use Shared Preferences. We would discuss all these topics in our tutorial. Now the main part is know the job of it. Shared Preferences is use to store a small amount of data locally in application memory using a Unique KEY. We can also retrieve the stored data from that KEY and also delete it if we required. The good thing is that it stores the data permanently in app’s memory so unless we remove the app or delete the data using its KEY, It will not be delete. So in this tutorial we would learn about Example of Shared Preferences in Flutter to Save Data Locally.
Question : Where we can use Shared Preferences ?
Answer : We can use it to store Entered Username and Password locally using Save me button. So there is no need to enter email password each time we login. We can also store app login season cookie in it.
Write Data in Shared Preferences :-
1 2 3 4 5 6 7 8 9 10 11 12 13 |
// Obtain shared preferences. final prefs = await SharedPreferences.getInstance(); // Save an integer value to 'counter' key. await prefs.setInt('counter', 10); // Save an boolean value to 'repeat' key. await prefs.setBool('repeat', true); // Save an double value to 'decimal' key. await prefs.setDouble('decimal', 1.5); // Save an String value to 'action' key. await prefs.setString('action', 'Start'); // Save an list of strings to 'items' key. await prefs.setStringList('items', <String>['Earth', 'Moon', 'Sun']); |
Read Data in Shared Preferences :-
1 2 3 4 5 6 7 8 9 10 |
// Try reading data from the 'counter' key. If it doesn't exist, returns null. final int? counter = prefs.getInt('counter'); // Try reading data from the 'repeat' key. If it doesn't exist, returns null. final bool? repeat = prefs.getBool('repeat'); // Try reading data from the 'decimal' key. If it doesn't exist, returns null. final double? decimal = prefs.getDouble('decimal'); // Try reading data from the 'action' key. If it doesn't exist, returns null. final String? action = prefs.getString('action'); // Try reading data from the 'items' key. If it doesn't exist, returns null. final List<String>? items = prefs.getStringList('items'); |
Contents in this project Example of Shared Preferences in Flutter to Save Data Locally :-
1. First of all we have to install shared_preferences 2.0.13 Pub package in our flutter project. So open your flutter project Root directory in Command Prompt or Terminal and execute below command.
1 |
flutter pub add shared_preferences |
2. Now we’re ready to go. Open your project’s main.dart file and import material.dart, dart:async and shared_preferences.dart package.
1 2 3 |
import 'package:flutter/material.dart'; import 'dart:async'; import 'package:shared_preferences/shared_preferences.dart'; |
3. Creating void main runApp() method and here we would call our MyApp class.
1 |
void main() => runApp(MyApp()); |
4. Creating MyApp extends StatelessWidget. In this class we would call our Child() class.
1 2 3 4 5 6 7 8 9 10 11 |
class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: const Text("Shared Preferences in Flutter"), ), body: Center(child: Child()))); } } |
5. Creating Child extends StatefulWidget class. In this class we would make createState() method and make our main Home class.
1 2 3 |
class Child extends StatefulWidget { Home createState() => Home(); } |
6. Creating our main Home extends State<Child> class.
1 2 3 4 5 |
class Home extends State<Child> { } |
7. Creating a TextEditingController object named as T_controller. It is used to get TextField entered value.
1 |
TextEditingController T_controller = new TextEditingController(); |
8. Creating a SharedPreferences object named as s_prefs.
1 |
late SharedPreferences s_prefs; |
9. Creating a String variable named as temp with empty value. It is used to store the saved shared preferences key and show into Text widget.
1 |
String temp = ''; |
10. Creating a ASYNC type of function named as _saveToShared_Preferences. In this function we would first make Instance of shared preferences. Now save the TextField entered value using KEY.
1 2 3 4 |
_saveToShared_Preferences() async { s_prefs = await SharedPreferences.getInstance(); s_prefs.setString("KEY_1", T_controller.text.toString()); } |
11. Creating another function named as _showSavedValue(). In this function we would retrieve the locally save value using the Key again and store into temp variable.
1 2 3 4 5 6 |
_showSavedValue() async { s_prefs = await SharedPreferences.getInstance(); setState(() { temp = s_prefs.getString("KEY_1").toString(); }); } |
12. Creating another function named as _delete_Shared_Preferences(). In this function we would delete the saved value.
1 2 3 4 5 6 7 |
_delete_Shared_Preferences() async { s_prefs = await SharedPreferences.getInstance(); s_prefs.remove("KEY_1"); setState(() { temp = " "; }); } |
13. Creating Widget Build area -> Now we would make 1 TextField widget, 1 Text widget and 3 Button widgets.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
Widget build(BuildContext context) { return Scaffold( body: SafeArea( top: true, child: Center( child: Column( crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ Container( padding: const EdgeInsets.fromLTRB(10, 0, 10, 0), margin: const EdgeInsets.fromLTRB(0, 15, 0, 0), child: TextField( controller: T_controller, decoration: const InputDecoration( labelText: 'Enter Text Here....', border: OutlineInputBorder(), ))), Container( margin: const EdgeInsets.fromLTRB(10, 15, 0, 0), child: ElevatedButton( child: const Text('Store Value in Shared Preferences'), onPressed: () => _saveToShared_Preferences(), style: ElevatedButton.styleFrom( primary: Colors.green, ), )), Container( margin: const EdgeInsets.fromLTRB(10, 10, 0, 0), child: ElevatedButton( child: const Text( 'Display Value Stored in Shared Preferences'), onPressed: () => _showSavedValue(), style: ElevatedButton.styleFrom( primary: Colors.green, ), )), Container( margin: const EdgeInsets.fromLTRB(10, 10, 0, 0), child: ElevatedButton( child: const Text( 'Delete Value Stored in Shared Preferences'), onPressed: () => _delete_Shared_Preferences(), style: ElevatedButton.styleFrom( primary: Colors.green, ), )), Container( margin: const EdgeInsets.fromLTRB(10, 10, 0, 0), child: Text( '${temp.toString()}', style: const TextStyle(fontSize: 25, color: Colors.black), textAlign: TextAlign.center, )) ], ), ))); } |
14. Complete source code for main.dart file :-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 |
import 'package:flutter/material.dart'; import 'dart:async'; import 'package:shared_preferences/shared_preferences.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: const Text("Shared Preferences in Flutter"), ), body: Center(child: Child()))); } } class Child extends StatefulWidget { Home createState() => Home(); } class Home extends State<Child> { TextEditingController T_controller = new TextEditingController(); late SharedPreferences s_prefs; String temp = ''; _saveToShared_Preferences() async { s_prefs = await SharedPreferences.getInstance(); s_prefs.setString("KEY_1", T_controller.text.toString()); } _showSavedValue() async { s_prefs = await SharedPreferences.getInstance(); setState(() { temp = s_prefs.getString("KEY_1").toString(); }); } _delete_Shared_Preferences() async { s_prefs = await SharedPreferences.getInstance(); s_prefs.remove("KEY_1"); setState(() { temp = " "; }); } @override Widget build(BuildContext context) { return Scaffold( body: SafeArea( top: true, child: Center( child: Column( crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ Container( padding: const EdgeInsets.fromLTRB(10, 0, 10, 0), margin: const EdgeInsets.fromLTRB(0, 15, 0, 0), child: TextField( controller: T_controller, decoration: const InputDecoration( labelText: 'Enter Text Here....', border: OutlineInputBorder(), ))), Container( margin: const EdgeInsets.fromLTRB(10, 15, 0, 0), child: ElevatedButton( child: const Text('Store Value in Shared Preferences'), onPressed: () => _saveToShared_Preferences(), style: ElevatedButton.styleFrom( primary: Colors.green, ), )), Container( margin: const EdgeInsets.fromLTRB(10, 10, 0, 0), child: ElevatedButton( child: const Text( 'Display Value Stored in Shared Preferences'), onPressed: () => _showSavedValue(), style: ElevatedButton.styleFrom( primary: Colors.green, ), )), Container( margin: const EdgeInsets.fromLTRB(10, 10, 0, 0), child: ElevatedButton( child: const Text( 'Delete Value Stored in Shared Preferences'), onPressed: () => _delete_Shared_Preferences(), style: ElevatedButton.styleFrom( primary: Colors.green, ), )), Container( margin: const EdgeInsets.fromLTRB(10, 10, 0, 0), child: Text( '${temp.toString()}', style: const TextStyle(fontSize: 25, color: Colors.black), textAlign: TextAlign.center, )) ], ), ))); } } |
Screenshots :-