Open In App

Flutter – Shared Preferences to Keep User Logged In

Last Updated : 02 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

If you implement Sign-in and Sign-out features in your Android Application. Then you must need the user logged in if the user previously logged in and the user logged out if the user is previously logged-out. So we are in this article implementing How to use shared preferences to logged-in to the user. A sample video is given below to get an idea about what we are going to do in this article.

Approach

Now we are giving a simple idea of how to do that, If we create a bool variable to hold the state of the user logged in or logged out. If the user logged in we can store true in the variable and if the user is not logged in we can store false in the variable. Now again problem is that this variable is created at the time the application is running and destroyed when the application is not running, Now how to fetch this value to check whether the user logged in or not? 

Shared Preferences do that work, Shared Preferences is the short value data storage that persists or save the small data into the device storage.  Now all things are clear, Fetch every time value of the variable and Navigate the screen according to this variable.

Note: Shared Preferences is not the database, it simply stores the small value. For databases, you can refer to Firebase, SQLITE, MongoDB, etc.

Step By Step Implementation

Step 1: Create a New Project in Android Studio

To set up Flutter Development on Android Studio please refer to Android Studio Setup for Flutter Development, and then create a new project in Android Studio please refer to Creating a Simple Application in Flutter. After successfully creating the flutter application, Next move forward to add the dependency we need.

Step 2: Add the Package into the pubspec.yaml file

Run this command:

With Flutter:

$ flutter pub add shared_preferences

This will add a line like this to your package’s pubspec.yaml (and run an implicit flutter pub get):

dependencies:
 shared_preferences: ^2.0.15

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

Import it:

Now in your Dart code, you can use:

import 'package:shared_preferences/shared_preferences.dart';

Now we have to create a two-screen in our Flutter application.

  • Home Screen – Home screen will show if the user successfully login. 
  • Log in Screen – Log in screen will show if the user in not login or the user is logged out.

Step 3: Create a Home screen or stateless widget

Dart




class Home extends StatelessWidget {
  const Home({super.key});
 
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Home'),
      ),
      body: Center(
          child: ElevatedButton(
              onPressed: () {
                Helper.saveUserLoggedInSharedPreference(false);
                Navigator.pushReplacement(
                  context,
                  MaterialPageRoute(
                    builder: (context) => Signin(),
                  ),
                );
              },
              child: Text('Sign out'))),
    );
  }
}


Home screen contains the centered Elevated button that is used to logout the user from the application and navigates to Signin screen. And also save the shared preference to false which means the user is now logged out from the application and should try to Sign in again. 

Step 4: Create the Sign in screen or stateless widget.

Dart




class Signin extends StatelessWidget {
  const Signin({super.key});
 
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: ElevatedButton(
          child: Text("Log In"),
          onPressed: () {
            Helper.saveUserLoggedInSharedPreference(true);
            Navigator.pushReplacement(
              context,
              MaterialPageRoute(
                builder: (context) => Home(),
              ),
            );
          },
        ),
      ),
    );
  }
}


Sign in screen contains the Centered Elevated button that is used to navigate the user to the home screen and save the sharedpreference to true which means the user is now logged in to the application. Now last, More important, our main login goes here, Now we have to check during the app launching whether the user is Previously logged in or not.  If the user previously logged in we can simply navigate it to the home screen otherwise it should go to the Sign in screen and should try to log in again.

Dart




import 'dart:async';
import 'package:flutter/material.dart';
import 'package:sharedprefrecestouserloggedin/home.dart';
import 'package:sharedprefrecestouserloggedin/share.dart';
 
void main() {
 runApp(MaterialApp(
   home: myApp(),
   theme: ThemeData(primarySwatch: Colors.green),
 ));
}
 
class myApp extends StatefulWidget {
 const myApp({super.key});
 
 @override
 State<myApp> createState() => _myAppState();
}
 
class _myAppState extends State<myApp> {
 late bool userIsLoggedIn;
 
 getLoggedInState() async {
   await Helper.getUserLoggedInSharedPreference().then((value) {
     setState(() {
       userIsLoggedIn = value!;
     });
   });
 }
 
 @override
 void initState() {
   super.initState();
 
   getLoggedInState();
   Timer(
     Duration(seconds: 3),
     () => Navigator.pushReplacement(
       context,
       MaterialPageRoute(
           builder: (context) => userIsLoggedIn != null
               ? userIsLoggedIn
                   ? Home()
                   : Signin()
               : Signin()),
     ),
   );
 }
 
 @override
 Widget build(BuildContext context) {
   return MaterialApp(
     title: "Shared Preferences",
     debugShowCheckedModeBanner: false,
     home: Scaffold(
         body: Center(
       child: CircularProgressIndicator(),
     )),
   );
 }
}


Output



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads