X

Flutter shared preference | User login using shared preferences

 

Flutter shared preference :

Flutter shared preference is used to save the data in the application and can be retrieved later for usage.It is considered as the light weight storage option available in mobile apps both for android and iOS.

The most important usage of flutter shared preference is to store user login credential’s, almost every app use this mechanism so in this part of the tutorial on Flutter shared preference we will discuss a detailed implementation.

The pattern followed in storing is a key and value, there will be a key for every value and they are store and retrieved based on these keys, every key should be unique.

Sometimes in apps where there are forms to be filled and to store the data on inappropriate  app closure we may use flutter shared preference.

 

Flutter shared preference video tutorial :

Go through the below tutorial for more detailed explanation on shared preferences.

 

Project Structure :

This image depicts the project structure implementation of flutter shared preferences.

 

pubspec.yaml :

Add flutter shared preference dependency as below use the latest version for avoiding the code level issues.

dependencies:
  flutter:
    sdk: flutter
  shared_preferences: 0.5.8

 

main.dart :

Initialize with void main() and provide the default class MyApp()

void main() {
  runApp(MyApp());
}

 

Add shared preference

SharedPreferences localStorage;

 

Add TextEditingControllers using which we can handle / fetch the data from text views.

TextEditingController emailController = new TextEditingController();
TextEditingController pwdController = new TextEditingController();

 

Initialize shared preferences using async method and get instance.

static Future init() async {
  localStorage = await SharedPreferences.getInstance();
}

 

Design Field Email Id

Container(
  margin: EdgeInsets.symmetric(vertical: 10),
  child: Column(
    crossAxisAlignment: CrossAxisAlignment.start,
    children: <Widget>[
      Text(
        "Email Id:",
        style:
            TextStyle(fontWeight: FontWeight.bold, fontSize: 15),
      ),
      SizedBox(
        height: 10,
      ),
      TextField(
          controller: emailController,
          obscureText: false,
          decoration: InputDecoration(
              border: InputBorder.none,
              fillColor: Color(0xfff3f3f4),
              filled: true))
    ],
  ),
),

 

Design Field Password

Container(
  margin: EdgeInsets.symmetric(vertical: 10),
  child: Column(
    crossAxisAlignment: CrossAxisAlignment.start,
    children: <Widget>[
      Text(
        "Password :",
        style:
            TextStyle(fontWeight: FontWeight.bold, fontSize: 15),
      ),
      SizedBox(
        height: 10,
      ),
      TextField(
          controller: pwdController,
          obscureText: true,
          decoration: InputDecoration(
              border: InputBorder.none,
              fillColor: Color(0xfff3f3f4),
              filled: true))
    ],
  ),
),

 

Add a login button and provide save to the onPressed function and provide the title for Text widget.

RaisedButton(
  onPressed: save,
  child: Text('Login'),
),

 

Save data into shared preferences using async method save()

save() async {
  await MyApp.init();
  localStorage.setString('email', emailController.text.toString());
  localStorage.setString('password', pwdController.text.toString());

}

 

Display data from shared preferences is data is not null.

if (localStorage != null)
  Padding(
    padding: const EdgeInsets.all(15.0),
    child: Text("User Logged in!!! ->  Email Id: ${localStorage.get('email')}  Password: ${localStorage.get('password')}",style: TextStyle(fontSize: 20),),
  ),

 

Full Code :

Providing the full code for flutter shared preferences implementation.

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

void main() {
  runApp(MyApp());
}

SharedPreferences localStorage;

TextEditingController emailController = new TextEditingController();
TextEditingController pwdController = new TextEditingController();

class MyApp extends StatelessWidget {
  static Future init() async {
    localStorage = await SharedPreferences.getInstance();
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return MaterialApp(
      home: MyHome(),
    );
  }
}

class MyHome extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      body: Padding(
        padding: const EdgeInsets.all(30.0),
        child: Center(
          child: Column(
            children: <Widget>[
              Padding(
                padding: EdgeInsets.only(top: 200),
              ),
              Container(
                margin: EdgeInsets.symmetric(vertical: 10),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Text(
                      "Email Id:",
                      style:
                          TextStyle(fontWeight: FontWeight.bold, fontSize: 15),
                    ),
                    SizedBox(
                      height: 10,
                    ),
                    TextField(
                        controller: emailController,
                        obscureText: false,
                        decoration: InputDecoration(
                            border: InputBorder.none,
                            fillColor: Color(0xfff3f3f4),
                            filled: true))
                  ],
                ),
              ),
              Container(
                margin: EdgeInsets.symmetric(vertical: 10),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Text(
                      "Password :",
                      style:
                          TextStyle(fontWeight: FontWeight.bold, fontSize: 15),
                    ),
                    SizedBox(
                      height: 10,
                    ),
                    TextField(
                        controller: pwdController,
                        obscureText: true,
                        decoration: InputDecoration(
                            border: InputBorder.none,
                            fillColor: Color(0xfff3f3f4),
                            filled: true))
                  ],
                ),
              ),
              Padding(
                padding: EdgeInsets.only(top: 50),
              ),
              RaisedButton(
                onPressed: save,
                child: Text('Login'),
              ),

              Padding(
                padding: EdgeInsets.only(top: 50),
              ),
              if (localStorage != null)
                Padding(
                  padding: const EdgeInsets.all(15.0),
                  child: Text("User Logged in!!! ->  Email Id: ${localStorage.get('email')}  Password: ${localStorage.get('password')}",style: TextStyle(fontSize: 20),),
                ),
            ],
          ),
        ),
      ),
    );
  }
}


save() async {
  await MyApp.init();
  localStorage.setString('email', emailController.text.toString());
  localStorage.setString('password', pwdController.text.toString());

}

 

Flutter shared preference Output :

This screen below depicts the usage of flutter shared preferences.

If you have any comments on this tutorial flutter shared preference do let us know in the comment section below.If you like this tutorial do like and share this tutorial for more interesting tutorials.

abhishek:
Related Post

This website uses cookies.