Please assign a menu to the primary menu location under MENU

Codeplayon
Codeplayon
  • Home
  • DSA
  • Jetpack
  • Flutter
  • Android
    • Android Tutorials
    • Android development
  • Kotlin
  • 5G
  • 4G LTE
    • IoT
  • e learning
  • Blog
HomeFlutter Tutorial for beginnerflutter shared preferences example
Flutter Tutorial for beginner

flutter shared preferences example

Codeplayon2 years agoJuly 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

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

Table of Contents

  • Flutter shared preference User login using shared preferences
    • Main.dart file Source code
    • HomePage.Dart file source code .

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 keyandvalue-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 Twittershare on Pinterestshare on LinkedIn share on Tumblrshare on Redditshare on VKontakteshare on Email
add a comment
CodeplayonJune 22, 2021
simple calculator in flutter
how to disable screenshot in android programmatically
profile for Codeplayon on Stack Exchange, a network of free, community-driven Q&A sites

find me on socials

latest posts

How can I prepare for the ITIL Foundation certification exam?

6 days agoSeptember 27, 2023

DevOps training – What is the role of DevOps professionals in the modern companies?

2 weeks agoSeptember 25, 2023

A Guide to the Best Disinfectant Floor Cleaner for Your Home

2 weeks ago

The 3 Best Websites for Finding House Cleaning Jobs

2 weeks agoSeptember 18, 2023
Google News
Google News

Search

Contact Info

Contact information that feels like a warm, friendly smile.

Phone:9876543210
Email:info.codeplayon@gmail.com
Website:Codeplayon

popular posts

Joinpd

JoinPD.com – Peardeck Login Full Guide Details 2023

1 month agoSeptember 18, 2023
Best StreamEast live Alternatives For Free Sports Streaming

streameast.live For NFL Free Sports Streaming And Streameast Alternatives

8 months agoFebruary 15, 2023
Disneyplus.com/begin

Disneyplus.com begin code for Disney+ account login 2022

2 years agoFebruary 15, 2023
  • How can I prepare for the ITIL Foundation certification exam?
  • DevOps training – What is the role of DevOps professionals in the modern companies?
  • A Guide to the Best Disinfectant Floor Cleaner for Your Home
  • The 3 Best Websites for Finding House Cleaning Jobs
  • By Purchasing Reliable Instagram Followers, You Can Significantly Boost Your Online Presence on Instagram

Copyright © 2023 codeplayon

Go to mobile version