• Home
  • AI
  • DSA
  • iOS
  • Flutter
  • Android
    • Jetpack
    • Android Tutorials
    • Android development
    • Android Kotlin
  • 5G
  • 4G LTE
    • IoT
  • E-learning
  • Blog
  • Streaming
Tuesday, November 25, 2025
  • Home
  • AI
  • DSA
  • iOS
  • Flutter
  • Android
    • Jetpack
    • Android Tutorials
    • Android development
    • Android Kotlin
  • 5G
  • 4G LTE
    • IoT
  • E-learning
  • Blog
  • Streaming
subscribe
subscribe to my newsletter!

"Get all latest content delivered straight to your inbox."

[mc4wp_form id="36"]
Codeplayon
Codeplayon
  • Home
  • AI
  • DSA
  • iOS
  • Flutter
  • Android
    • Jetpack
    • Android Tutorials
    • Android development
    • Android Kotlin
  • 5G
  • 4G LTE
    • IoT
  • E-learning
  • Blog
  • Streaming
HomeFlutter Tutorialflutter shared preferences example
Jun. 22, 2021 at 4:23 am
Flutter Tutorial

flutter shared preferences example

4 years agoJanuary 15, 2024
Simple flutter login screen UI example
6.2kviews

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
Shivam MalikJune 22, 2021

Shivam Malik

Welcome to my blog! I’m Ritu Malik, and here at Codeplayon.com, we are dedicated to delivering timely and well-researched content. Our passion for knowledge shines through in the diverse range of topics we cover. Over the years, we have explored various niches such as business, finance, technology, marketing, lifestyle, website reviews and many others. Pinay Viral sfm compile AsianPinay taper fade haircut Pinay flex Pinay hub pinay Viral Fsi blog com pinay yum pinayyum.com baddies hub asianpinay.com tech crusader
view all posts
simple calculator in flutter
how to disable screenshot in android programmatically

You Might Also Like

comparison between Android Native and Flutter for app development
Flutter Tutorial

comparison between Android Native and Flutter for app development

Shivam Malik
flutter showcase example
Flutter Tutorial

flutter showcase example & flutter showcase package

Shivam Malik
Download csv file and save in downloads folder in flutter
Flutter Tutorial

flutter Download csv file and save in downloads folder

Shivam Malik
How to send multipart file with Flutter
Flutter Tutorial

How to send multipart file with Flutter 2023

Shivam Malik
flutter http get request with parameters example
Flutter Tutorial

flutter http get request with parameters example 2023

Shivam Malik
flutter barcode & QR code scanner example
Flutter Tutorial

flutter barcode & QR code scanner example

Shivam Malik

Get Even More

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

latest posts

comparison between Android Native and Flutter for app development
Flutter Tutorial

comparison between Android Native and Flutter for app development

Shivam Malik
2
Kotlin Coroutines with Retrofit
Android Kotlin

Kotlin Coroutines with Retrofit in 2026

Shivam Malik
91
E-learning

What is Formative Evaluation?

Shivam Malik
538
the://vital-mag.net blog​
Blog

The //Vital-Mag.net Blog:Proven Strategies to Skyrocket Blogging Success

Shivam Malik
748

find me on socials

Search

Contact Info

Contact information that feels like a warm, friendly smile.

Email:Info.codeplayon@gmail.com
Website:Codeplayon

popular posts

Joinpd.con code

How to get Pear Deck Join Code For JoinPD.con 2025?

3 months agoNovember 3, 2025
rice purity test

What is your Rice Purity Test Score: Check Score – 2025

11 months agoNovember 2, 2025
Disneyplus.com/begin

How to Activate Disneyplus.com begin account 2025

4 months agoAugust 4, 2025
Sitemap.Html
  • comparison between Android Native and Flutter for app development
  • Kotlin Coroutines with Retrofit in 2026
  • What is Formative Evaluation?
  • The //Vital-Mag.net Blog:Proven Strategies to Skyrocket Blogging Success
  • Google Meet The 360-Degree Background
Codeplayon
  • Privacy Policy

Copyright © 2024 Codeplayon | NewsMozi Asian Pinay.com Taper Fade Haircut sfm compile club Asian Pinay pinayhub.com pinayflex.com pinay Viral Fsi blog com