Flutter SharedPreferences Tutorials and Other Useful shared_preferences Libraries

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

shared_preferences

The plugin wraps platform-specific persistent storage for simple data (NSUserDefaults on iOS and macOS, SharedPreferences on Android, etc.)

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));
  }
}

rx_shared_preferences

This is a stream based wrapper over shared_preferences, allowing reactive key-value storage with rxdart Stream observation.

final rxPrefs = RxSharedPreferences(await SharedPreferences.getInstance());

//methods supported to read and save data
Future<bool> containsKey(String key);
Future<dynamic> get(String key);
Future<bool> getBool(String key);
Future<double> getDouble(String key);
Future<int> getInt(String key);
Future<Set<String>> getKeys();
Future<String> getString(String key);
Future<List<String>> getStringList(String key);

Future<bool> clear();
Future<void> reload();
Future<bool> commit();
Future<bool> remove(String key);
Future<bool> setBool(String key, bool value);
Future<bool> setDouble(String key, double value);
Future<bool> setInt(String key, int value);
Future<bool> setString(String key, String value);
Future<bool> setStringList(String key, List<String> value);

streaming_shared_preferences

streaming_shared_preferences adds reactive functionality on top of shared_preferences. It can do everything SharedPreferences can, while adding the function of listening to changes in keys.

final preferences = await StreamingSharedPreferences.instance;

// Get a reference to the counter value and provide a default value 
// of 0 in case it is null.
Preference<int> counter = preferences.getInt('counter', defaultValue: 0);

// "counter" is a Preference<int> - it can do anything a Stream<int> can.
// We're just going to listen to it and print the value to console.
counter.listen((value) {
  print(value);
});

// Somewhere else in your code, update the value.
counter.setValue(1);

// This is exactly same as above, but the above is more convenient.
preferences.setInt('counter', 2);

encrypted_shared_preferences

This is the same as Shared Preferences but it saves data as encrypted values. Data is decrypted when retrieved. 

EncryptedSharedPreferences encryptedSharedPreferences = EncryptedSharedPreferences();

//read data
encryptedSharedPreferences.getString('username').then((String value) {
    print(value); 
});
//save data
encryptedSharedPreferences.setString('username', 'admin').then((bool success) {
    print(success);
});

glutton

Glutton can save data as key-value securely. Stored data is also encrypted.

//save
bool isSuccess = await Glutton.eat(key, data);
//read
dynamic data = await Glutton.vomit(key);
//check if data exist
bool isExist = await Glutton.have(key);
//remove
bool isSuccess = await Glutton.digest(key);
//clear all
await Glutton.flush();

Leave a Comment

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