Shared Preferences in Flutter - shared preferences to keep user logged

Hi Guys, Welcome to Proto Coders Point, In this Flutter Tutorial we will learn how to use shared preferences in Flutter Application Development to keep users logged In.

In this example we gonna make use of flutter shared Preferences library, to keep logged in users data.

Brief about Shared Preferences?

In mobile app development their are many ways to shore data of an application. One of the way to shore data in mobile device itself is by making use of Shared Preferences.

It allows you to save and retrieve data in a form of key,value pair.

Video Tutorial

so Let’s begin adding and implementing Shared Preferences in Flutter with example of keeping users logged in.

In order to use this library, you need to first add the package in your flutter project to do so follow below 2 steps

Step 1 : Adding SharedPreferences Dependencies code

Visit the official website to get latest version of this library here

dependencies:
  shared_preferences: ^0.5.6+2 //add this line

Under you Flutter Project open pubspec.yaml file and add the dependences as show in below image.

adding shared preferences flutter dependences library

Step 2: Import the Flutter Shared Preferences package

Now, once you have added the dependencies in your flutter project now you can make use of the package through out your project just by importing the package.

How to import SharedPreferences ?

import 'package:shared_preferences/shared_preferences.dart';

Open dart file where you want to use shared Preferences to store and retrieve data, in my case it main.dart.

Note : This plugin must be used only to hold small data, in other words this plugin should not be used to store any kind of critical data.

In order to use shared preferences, you have to call a method getSharedPreferences() that returns a SharedPreference instance pointing to the file that contains the values of preferences.

You need to call  a method SharedPreferences.getInstance and create a dart object names prefsdata.

SharedPreferences prefsdata = await SharedPreferences.getInstance();

Then, you can make use of this object ( prefsdata ) to store and retrieve data from sharedpreferences database.

How to store data in shared Preferences in flutter?

logindata.setString('username', username);

Here ‘username’ is a key and username is a value.

shared preferences key value example

How to retrieve data from shared Preferences?

String user = logindata.getString('username');

In the above snippet code ‘username’ is the key that holds the value.

Shared Preferences in Flutter – shared preferences to keep user logged?

In this Flutter tutorial for shared Preferences example i am going to create a simple login form note : without any backend database ( it’s just a dummy project )

for this project you need two dart pages. First to display login page (main.dart), Second to show successfully logged in user data ( mainpage.dart )

main.dart

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: '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();

  SharedPreferences logindata;
  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"),
            )
          ],
        ),
      ),
    );
  }
}

The above dart code will result UI something like below screenshot

Login screen for shared preferences example

mainPage.dart

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:fluttersharedpreferences/main.dart';
import 'package:shared_preferences/shared_preferences.dart';

class MainPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyDashboard(),
    );
  }
}

class MyDashboard extends StatefulWidget {
  @override
  _MyDashboardState createState() => _MyDashboardState();
}

class _MyDashboardState extends State<MyDashboard> {
  SharedPreferences logindata;
  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 PROTO CODERS POINT  $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'),
            )
          ],
        ),
      ),
    );
  }
}

Result

logged in user welcome screen with retrived data from shared preferences-min

 

Comments are closed.