flutter shared preferences example
Hi everyone In this flutter tutorial I share aflutter shared preferences example using dart. We make a flutter example app in this example we make a login app to save data and manage login session for use. User can enter login details and login into App and redirect to the home screen. Next time when the user comes in-app session is managed and directly redirect to the home page. In if you can log out re-direct to the home page. so let’s make an easy example flutter shared preferences example.
Flutter shared preference User login using shared preferences
shared preference is used to save the data and retrieve data as per requirement. It is a lightweight storage option in mobile apps both for android and iOS. And in this example, we used flutter shared preference to store user login details. Almost every developer used this way to manage user session. So in this flutter shared_preferences example, we will discuss in detail how to implement it.
You can follow this way to stores data in shared preference is a key and value-form, there will be a key for every value and store & retrieved based on these keys, every key should be unique.
In this Flutter shared preference I am using shared_preferences 0.5.8 dependencies. Add this dependence in your pubspace yaml file and pub get
shared_preferences: ^0.5.8
Let start on Project make a flutter project and add dependence and after that, you can clear your main dart file source code. In your main. dart file we create a login page UI and here can entry the user details and on button click store the data in share preferences. so follow full source code on these main.dart file.
Main.dart file Source code
import 'package:flutter/material.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'mainPage.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Codeplayon Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyLoginPage(), ); } } class MyLoginPage extends StatefulWidget { @override _MyLoginPageState createState() => _MyLoginPageState(); } class _MyLoginPageState extends State<MyLoginPage> { // Create a text controller and use it to retrieve the current value // of the TextField. final username_controller = TextEditingController(); final password_controller = TextEditingController(); late SharedPreferences logindata; late bool newuser; @override void initState() { // TODO: implement initState super.initState(); check_if_already_login(); } void check_if_already_login() async { logindata = await SharedPreferences.getInstance(); newuser = (logindata.getBool('login') ?? true); print(newuser); if (newuser == false) { Navigator.pushReplacement( context, new MaterialPageRoute(builder: (context) => MyDashboard())); } } @override void dispose() { // Clean up the controller when the widget is disposed. username_controller.dispose(); password_controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(" Shared Preferences"), ), body: Center( child: Column( crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ Text( "Login Form", style: TextStyle(fontSize: 30, fontWeight: FontWeight.bold), ), Text( "To show Example of Shared Preferences", style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold), ), Padding( padding: const EdgeInsets.all(15.0), child: TextField( controller: username_controller, decoration: InputDecoration( border: OutlineInputBorder(), labelText: 'username', ), ), ), Padding( padding: const EdgeInsets.all(15.0), child: TextField( controller: password_controller, decoration: InputDecoration( border: OutlineInputBorder(), labelText: 'Password', ), ), ), RaisedButton( textColor: Colors.white, color: Colors.blue, onPressed: () { String username = username_controller.text; String password = password_controller.text; if (username != '' && password != '') { print('Successfull'); logindata.setBool('login', false); logindata.setString('username', username); Navigator.push(context, MaterialPageRoute(builder: (context) => MyDashboard())); } }, child: Text("Log-In"), ) ], ), ), ); } }
After creating the login form you can create a Home page dart file. On this Home page, we make a button for logout and when the user clicks on Log out app redirect to the Login page to manage user sessions. In this topic, we cover also the flutter login session example. Let make a Home page with logout button.
HomePage.Dart file source code .
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'main.dart'; import 'package:shared_preferences/shared_preferences.dart'; class MainPage extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Codeplayon Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyDashboard(), ); } } class MyDashboard extends StatefulWidget { @override _MyDashboardState createState() => _MyDashboardState(); } class _MyDashboardState extends State<MyDashboard> { late SharedPreferences logindata; late String username; @override void initState() { // TODO: implement initState super.initState(); initial(); } void initial() async { logindata = await SharedPreferences.getInstance(); setState(() { username = logindata.getString('username'); }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("Shared Preference Example"), ), body: Padding( padding: const EdgeInsets.all(26.0), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Center( child: Text( 'Welcome To Codeplayon.com $username', style: TextStyle(fontSize: 25, fontWeight: FontWeight.bold), ), ), RaisedButton( onPressed: () { logindata.setBool('login', true); Navigator.pushReplacement(context, new MaterialPageRoute(builder: (context) => MyLoginPage())); }, child: Text('LogOut'), ) ], ), ), ); } }
after add these code run your flutter Application and see output. and learn how to use sharedpreferences in flutter. Also in here we shared preferences to keep user logged in flutter.