Flutter SharedPreferences Tutorials

 Shared Preferences is a way to store data key-value pair in the Android and iOS.

The shared_preferences library can be downloaded here.

Table of Contents

Example

import 'package:shared_preferences/shared_preferences.dart';

class SharedPrefs {
	static Future<SharedPreferences> get prefs => SharedPreferences.getInstance();

	static void saveUsername(String username) async{
		final p = await prefs;
		p.setString('USERNAME', username);
	}
	static Future<String> loadUsername() async{
		final p = await prefs;
		return p.getString('USERNAME') ?? 'demo';
	}
}

Store an object

class User {
  final int id;
  final String username;
  final String fullname;

  User(this.id, this.username, this.fullname);

  User.fromJson(Map<String, dynamic> json)
      : id = json['id'],   
        username = json['username'],
        fullname = json['fullname'];

  Map<String, dynamic> toJson() =>
      {
        'int': int,
        'username': username,
        'fullname': fullname,
      };
}
class UserPrefs {
  static Future<SharedPreferences> get prefs => SharedPreferences.getInstance();

  static void setUser(User user) async {
    final p = await prefs;
    p.setString('USER', jsonEncode(user.toJson()));
  }

  static Future<User> getUser() async {
    final p = await prefs;
    String userString = p.getString('USER');
    return User.fromJson(jsonDecode(userString));
  }
}

Leave a Comment

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

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close