How to store login credential in flutter 1000*600

How To Store Login Credentials? The Right Way In Flutter

Do you want to explore the process of storing login credentials? Want to know the right way to Flutter? If yes, then stay with this guide and collect all the essential factors available here. When you have used all the shared preferences for accessing tokens or saving login credentials, then this article from one of the best mobile app development agencies can help you.

When you are asked to develop the login screen, then you can find the auto-login feature or ‘remember me’ check box. The major thing you have to do is to save the token or login credentials into the local storage. Therefore when you come back to use the app once again, you can automatically find that your login credentials will be saved. Hence you don’t need to spend time on the login screen every time. 

Really it is a useful process to save time. But what about the login credentials security?

How to Secure Your Login Credentials?

Most of the users are afraid of storing their credentials in the Shared Preferences since it may be exposed to the attacker or hacker. They are not ready to lose all their data due to revealing their login credentials.

During that time, here comes the Flutter community with a great solution. Flutter developers are putting more effort into creating a better package to cover this scenario effectively.

shared_preferences is the best package that uses AES encryption with the Keystore for android OS and stores the data into keychains for iOS. The v5.0.0 android version also supports EncryptedShashared_preferencesredPreferences. 

Here you have to note one such thing for android the plugin is compatible with Android SDK 18+ while introducing the Keystore. Check out further to find out how to use the plugin for the login screen.

Also, Read This Post:

A Complete Guide to Enterprise Mobile App Development Process

How to Use The Plugin For the Login Screen?

First, you must get ready with the login that you are going to create.

While filling out the form with legal credentials and pushing the sign-in option, you have to store it in secure storage. When you come back to use the app once again, then you can find that all your login credentials will be auto-filled in that form.

It is a very simple login user interface with certain login business logic running behind it. After that, you have to begin the coding process.

SharedPreferences prefs = await SharedPreferences.getInstance();
int counter = (prefs.getInt('counter') ?? 0) + 1;
print('Pressed $counter times.');
await prefs.setInt('counter', counter);

First, you must have to add the package into pubspec.yaml file.

Then you must find the working of shared_preferences

Here you have to do some essential processes that are reported in README.md

It is a very simple package.

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() => runApp(const MyApp());
class MyApp extends StatefulWidget {
  const MyApp({super.key});
  @override
  _MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: 'Auto Login',
        theme: ThemeData(
          primarySwatch: Colors.blue,
        ),
        home: const MyHomePage());
  }
}
class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key});
  @override
  _MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
  TextEditingController nameController = TextEditingController();
  bool isLoggedIn = false;
  String name = '';
  @override
  void initState() {
    super.initState();
    autoLogIn();
  }
  void autoLogIn() async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    final String? userId = prefs.getString('username');
    if (userId != null) {
      setState(() {
        isLoggedIn = true;
        name = userId;
      });
      return;
    }
  }
  Future<void> logout() async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setString('username', "");
    setState(() {
      name = '';
      isLoggedIn = false;
    });
  }
  Future<void> loginUser() async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setString('username', nameController.text);
    setState(() {
      name = nameController.text;
      isLoggedIn = true;
    });
    nameController.clear();
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Auto Login Home Page'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            !isLoggedIn
                ? TextField(
                    textAlign: TextAlign.center,
                    controller: nameController,
                    decoration: const InputDecoration(
                        border: InputBorder.none,
                        hintText: 'Please enter your name'),
                  )
                : Text('You are logged in as $name'),
            const SizedBox(height: 10.0),
            ElevatedButton(
              onPressed: () {
                isLoggedIn ? logout() : loginUser();
              },
              child: isLoggedIn ? const Text('Logout') : const Text('Login'),
            )
          ],
        ),
      ),
    );
  }
}


Output:

In line 4, you can effectively create storage that can let you read and store data without any issues.

Then in line 7, you have to read and decrypt the string value that can be identified effectively by the key label or the null if the key is not available in the storage. Here you must remember the fact that the key should never be null. 

After that, at line 19, you have to store and then encrypt the value object that is identified effectively by the key label. When the key is already in the storage, then the associated value can be changed. When the value is null, then it will delete all the associated values for the given key.

Flutter Developers from Flutter Agency
Flutter Developers from Flutter Agency

Here you must need some use cases:

  • The FlutterSecureStorage storage instance;
  • The best approach to read data from the storage;
  • The best approach to writing data into the storage;

Now you have to get ready to define all the first two points.

Then you can store all the user credentials by defining the method _onFormSubmit(). Those methods can be actively associated with the official sign-in option. The method will completely take care of saving all the data in the storage by only validating the form.

After that, the method _readFromStorage() can be defined. One can call this method from initState() and you can retrieve the information in the storage through this manner before the construction of the user interface.

You can call the initState() method from the framework by creating the state. It can be called only one time before the user interface becomes drawn.

  • First, you need to enter the login credentials
  • After that, you have to click the sign-in option
  • Then when you open the app again, then you can find your credentials entered in the form already

You can find the entire link with the complete code after knowing the idea of storing login credentials. 

Now you have all the help regarding this essential app development process. The simple direction can’t let you add all the auto-login functionality to the app effectively. The stored information can be encrypted in secure storage. Through such simple steps, now the Flutter web app development can level up to the next level.fireb

Conclusion

The shared_preferences is very simple and can let you save all the user’s data in easy steps that can be encrypted in secure storage. You can extend the simple sample by storing some other user information effectively. Get knowledge of flutter technology with the help of Flutter Agency rich resources. They guide you all through the way and let you explore the process of storing login credentials and know the right way to Flutter. 

Frequently Asked Questions (FAQs)

1. What is used to maintain the users logged in the state?

One method is to maintain the state via the use of cookies. As cookies stores the set of the user’s detailed information, like the reference identifier for the database record, which holds customer information.

2. How to store login credentials in Flutter development?

We define the method _onFormSubmit() to store user credentials. This method action is connected with the sign-in button. Therefore, the method will take care of storing the data in the storage only if the form is validated.

3. Which command is utilized to list logged-in users?

A who command is used to display any users logged into the system. It is the command related to the w command, which is used to view information about the users on the machine and their processes.

Hire a Flutter Developer Now
Abhishek Dhanani

Written by Abhishek Dhanani

Abhishek Dhanani, a skilled software developer with 3+ years of experience, masters Dart, JavaScript, TypeScript, and frameworks like Flutter and NodeJS. Proficient in MySQL, Firebase, and cloud platforms AWS and GCP, he delivers innovative digital solutions.

Leave a comment

Your email address will not be published. Required fields are marked *


Discuss Your Project

Connect with Flutter Agency's proficient skilled team for your app development projects across different technologies. We'd love to hear from you! Fill out the form below to discuss your project.

Have Project For Us

Get in Touch

"*" indicates required fields

ready to get started?

Fill out the form below and we will be in touch soon!

"*" indicates required fields