How to store login credentials, the right way in Flutter

Tue, Feb 28, 2023

Read in 2 minutes

In this post we will discuss how to securely store user credentials locally in flutter.

Storing login credentials securely is essential for protecting user data and preventing unauthorized access. In Flutter, there are several ways to store login credentials securely:

  1. Use the Flutter Secure Storage plugin: The Flutter Secure Storage plugin provides a secure storage mechanism for sensitive data, including login credentials. This plugin uses the native Keychain (on iOS) or Keystore (on Android) to store the data securely. The stored data can only be accessed by the app that created it, and it remains encrypted even if the device is rooted or jailbroken.

To use the Flutter Secure Storage plugin, you can add it to your pubspec.yaml file:

dependencies:
  flutter_secure_storage: ^4.2.0

Then, you can use it to store the login credentials like this:

import 'package:flutter_secure_storage/flutter_secure_storage.dart';

final storage = FlutterSecureStorage();

// Store a key-value pair
await storage.write(key: 'username', value: 'example@domain.com');
await storage.write(key: 'password', value: 'password123');

// Read a value
String username = await storage.read(key: 'username');
String password = await storage.read(key: 'password');
  1. Use the SharedPreferences plugin: The SharedPreferences plugin provides a simple key-value storage mechanism for storing user preferences and other small data. However, it is not suitable for storing sensitive data like login credentials since it is not encrypted and can be accessed by other apps on the same device.

To use the SharedPreferences plugin, you can add it to your pubspec.yaml file:

dependencies:
  shared_preferences: ^2.0.6

Then, you can use it to store the login credentials like this:

import 'package:shared_preferences/shared_preferences.dart';

final prefs = await SharedPreferences.getInstance();

// Store a key-value pair
await prefs.setString('username', 'example@domain.com');
await prefs.setString('password', 'password123');

// Read a value
String username = prefs.getString('username');
String password = prefs.getString('password');

It is recommended to use the Flutter Secure Storage plugin for storing sensitive data like login credentials since it provides better security and protection against unauthorized access.


Shohruh AK



Category:

Flutter

Tags:



See Also

7 Most Popular Programming Languages
What is "do" in Dart?
ChatGPT Reviews: Pros, Cons, and Features
What is "deferred" in Dart?
What is "default" in Dart?