Hi everyone, this blog is about Shared Preferences using dart.
Here we will make a flutter app, in this example, we will make a login app to save data and as a result it will manage login sessions for users.
Users can enter login details and login into App and will be redirected to the home screen. Next time when the user comes in, app session is managed and as a result, it will directly redirect to the home page.
If you will logout from the home page by pressing the logout button. Then the user will be logged out and again redirect to the login page and will restart the session.
You may also check our Flutter app development services page
So let’s make an easy example using the shared preferences.
Now, first of all, we need to know what is Shared Preferences
Shared Preferences is a plugin for flutter apps. It is a local database that we use to store small data for the app. As we know, we can store data in shared preference in key-value pair form.
How can we use Shared Preferences
First of all, we need to add package dependencies to pubspec.yaml file.
First dependency for shared preferences
Second dependency for showing status of session on login logout actions.
1 2 |
shared_preferences: ^2.0.6 overlay_support: ^1.2.1 |
Now we have to create two files
- main.dart
- homepage.dart
main.dart file for the login screen and a homepage.dart file for the Homepage screen
main.dart Code :
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 |
import 'package:flutter/material.dart'; import 'package:overlay_support/overlay_support.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'homepage.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); SharedPreferences _prefs = await SharedPreferences.getInstance(); bool checkLogin = _prefs.getBool("isLoggedIn") ?? false; runApp(MyApp(checkLogin)); } class MyApp extends StatelessWidget { bool checkLogin; MyApp(this.checkLogin); // This widget is the root of your application. @override Widget build(BuildContext context) { return OverlaySupport.global( child: MaterialApp( debugShowCheckedModeBanner: false, home: checkLogin ? HomePage() : LoginPage(), ), ); } } class LoginPage extends StatefulWidget { @override _LoginPageState createState() => _LoginPageState(); } class _LoginPageState extends State<LoginPage> { Future<SharedPreferences> _prefs = SharedPreferences.getInstance(); final _formKey = GlobalKey<FormState>(); setLoginStatus() async { final SharedPreferences prefs = await _prefs; prefs.setBool("isLoggedIn", true); showSimpleNotification(Text("You are logged In"), background: Colors.green); Navigator.push( context, MaterialPageRoute(builder: (context) => HomePage())); } @override Widget build(BuildContext context) { final space = SizedBox(height: 20); return Scaffold( appBar: AppBar( title: Text("Login Page"), ), body: Center( child: Container( margin: EdgeInsets.fromLTRB(10.0, 0.0, 10.0, 0.0), child: Form( key: _formKey, child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ TextFormField( decoration: InputDecoration( border: new OutlineInputBorder( borderSide: new BorderSide(color: Colors.teal)), hintText: "username"), validator: (value) { if (value.isEmpty || value == null) { return "Enter username"; } else {} }, ), space, TextFormField( decoration: InputDecoration( border: new OutlineInputBorder( borderSide: new BorderSide(color: Colors.teal)), hintText: "password"), validator: (value) { if (value.isEmpty || value == null) { return "Enter password"; } else {} }, ), SizedBox(height: 50.0), Container( width: MediaQuery.of(context).size.width / 1.06, height: 40, child: ElevatedButton( onPressed: () { if (_formKey.currentState.validate()) { setLoginStatus(); } }, child: Text("Login"))) ], ), ), ), ), ); } } |
In this, we did our login page code and save the status of the session using shared preference after pressing the login button and navigate to the homepage page because the session status will logged in.
homepage.dart Code
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 |
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:overlay_support/overlay_support.dart'; import 'package:shared_preferences/shared_preferences.dart'; class HomePage extends StatelessWidget { Future<SharedPreferences> _prefs = SharedPreferences.getInstance(); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("HomePage"), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Container( alignment: Alignment.topCenter, width: MediaQuery.of(context).size.width / 1.06, height: 50.0, color: Colors.cyanAccent, child: Text( "Welcome to homepage", style: TextStyle( fontWeight: FontWeight.bold, color: Colors.black87, fontSize: 25.0), ), ), SizedBox( height: 50, ), Container( width: MediaQuery.of(context).size.width / 1.06, child: ElevatedButton( onPressed: () async { final SharedPreferences prefs = await _prefs; prefs.setBool("isLoggedIn", false); showSimpleNotification(Text("You are logged Out"), background: Colors.red); }, child: Text("Logout"))) ], ), ), ); } } |
In this, we did code for the homepage.dart and also provided a logout button to update the session status using shared preferences.
Here are images of login screen and homepage
I hope this blog will help you to learn about Shared Preferences and you will be able to implement them.
Happy Learning ✍️
Reference Link:
http://www.codeplayon.com/2021/06/flutter-shared-preferences-example/