• Home
  • DSA
  • 5G
  • 4G LTE
    • IoT
  • Android
    • Android Tutorials
    • Android development
  • Jetpack
  • Flutter
  • Kotlin
  • Blog
  • Apps
  • Streaming
codeplayon
codeplayon
  • Home
  • DSA
  • 5G
  • 4G LTE
    • IoT
  • Android
    • Android Tutorials
    • Android development
  • Jetpack
  • Flutter
  • Kotlin
  • Blog
  • Apps
  • Streaming
HomeFlutter Tutorial for beginnerflutter shared preferences example
Flutter Tutorial for beginner

flutter shared preferences example

CodeplayonJune 22, 2021July 8, 2022flutter exampleFlutter for Androidflutter login session exampleflutter remember loginFlutter shared preference | User login using shared preferencesflutter shared preferencesflutter shared_preferences exampleflutter sharedpreferences login example githubFlutter tutorialhow to get boolean value from sharedpreferences in flutterhow to use sharedpreferences in fluttershared preferences to keep user logged in flutter
Simple flutter login screen UI example
1.4kviews
0shares

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.

 

 

Tags :flutter exampleFlutter for Androidflutter login session exampleflutter remember loginFlutter shared preference | User login using shared preferencesflutter shared preferencesflutter shared_preferences exampleflutter sharedpreferences login example githubFlutter tutorialhow to get boolean value from sharedpreferences in flutterhow to use sharedpreferences in fluttershared preferences to keep user logged in flutter
share on Facebookshare on Twitter
CodeplayonJune 22, 2021
simple calculator in flutter
how to disable screenshot in android programmatically

Top Reviews

Video Widget

gallery

table-791167_1920
photo-1447078806655-40579c2520d6
home-984399_1920
create-865017_1920
carafe-791636_1920
still-life-594579_1920
View stream on flickr

subscribe to my newsletter!

"Get all latest content delivered straight to your inbox."
[mc4wp_form id="36"]

You Might Also Like

How to Protecting Flutter Application
Flutter Tutorial for beginner

How to Protecting Flutter Application

secure flutter application
Flutter Tutorial for beginner

How to secure flutter application code

flutter layout builder
Flutter Tutorial for beginner

Learn Flutter Layout Cheat Sheet

How to make Line Charts in Flutter
Flutter Tutorial for beginner

How to make Line Charts in Flutter

how to make a graph in flutter
Flutter Tutorial for beginner

Flutter Pie Chart Example

flutter date time picker example
Flutter Tutorial for beginner

flutter date time picker example

- Advertisement -

find me on socials

- Advertisement -

latest posts

Trollishly TikTok live

TikViral Ideas: How To TikTok Live Stream And Grow Your Community On TikTok?

How to create GridView using Jetpack Compose

August 6, 2022August 6, 2022

Lists using LazyColumn in Jetpack Compose

August 6, 2022August 6, 2022

5 Ways to Protect Landlord and Renter

August 5, 2022August 5, 2022

Trollishly : The Need For Creativity In TikTok For Better Future

August 1, 2022August 1, 2022
- Advertisement -

Search

Contact Info

Advertise your brand/services on our blog. You will surely get traffic and exposure from us. To know more about advertising opportunities, refer to our advertising page. Contact Us:

Email:info@codeplayon@gmail.com
- Advertisement -

popular posts

how to disable screenshot in android programmatically

how to disable screenshot in android programmatically

June 23, 2021
Android Splash Screen

android kotlin splash screen example

June 4, 2021
kotlin vs java

Kotlin vs Java performance Which is the Better

January 3, 2022January 4, 2022
- Advertisement -

latest posts

What is Git & Why Should You Use It

What is Git & Why Should You Use It 2022

April 20, 2022April 20, 2022
Google Chrome browser security vulnerability and how to avoid it in 2022

Google Chrome browser security vulnerability and how to avoid it in 2022

April 11, 2022April 11, 2022
MAC Vendor Lookup 1 e1648826097320

Ultimate Guide About Mac Address Lookup Tool | Code Play On

April 1, 2022April 1, 2022
- Advertisement -
Codeplayon
  • Home
  • DSA
  • 5G
  • 4G LTE
  • Android
  • Jetpack
  • Flutter
  • Kotlin
  • Blog
  • Apps
  • Streaming

Copyright © 2022 All Rights Reserved. Codeplayon