shared_preferences

122 阅读1分钟

简单数据存储可以采用shared_preferences

简单数据封装特定于平台的持久存储(iOS和macOS上的NSUserDefaults、Android上的SharedPreferences等)。数据可能会异步持久化到磁盘,并且不能保证返回后写入会持久化到硬盘,因此此插件不得用于存储关键数据

支持数据类型 intdoubleboolString and List<String>.

Write data

// Obtain shared preferences.
final SharedPreferences prefs = await SharedPreferences.getInstance();

// Save an integer value to 'counter' key.
await prefs.setInt('counter', 10);
// Save an boolean value to 'repeat' key.
await prefs.setBool('repeat', true);
// Save an double value to 'decimal' key.
await prefs.setDouble('decimal', 1.5);
// Save an String value to 'action' key.
await prefs.setString('action', 'Start');
// Save an list of strings to 'items' key.
await prefs.setStringList('items', <String>['Earth', 'Moon', 'Sun']);

Read data

// Try reading data from the 'counter' key. If it doesn't exist, returns null.
final int? counter = prefs.getInt('counter');
// Try reading data from the 'repeat' key. If it doesn't exist, returns null.
final bool? repeat = prefs.getBool('repeat');
// Try reading data from the 'decimal' key. If it doesn't exist, returns null.
final double? decimal = prefs.getDouble('decimal');
// Try reading data from the 'action' key. If it doesn't exist, returns null.
final String? action = prefs.getString('action');
// Try reading data from the 'items' key. If it doesn't exist, returns null.
final List<String>? items = prefs.getStringList('items');

Remove an entry

// Remove data for the 'counter' key.
await prefs.remove('counter');

封装 Storage

import 'package:shared_preferences/shared_preferences.dart';

class Storage {
  /// 设置字符串
  static setString(String key, String value) async {
    SharedPreferences sp = await SharedPreferences.getInstance();
    sp.setString(key, value);
  }
  /// 获取字符串
   static Future<String?> getString(String key) async {
    SharedPreferences sp = await SharedPreferences.getInstance();
    return sp.getString(key);
  }
  /// 根据key删除缓存
  static remove(String key) async {
    SharedPreferences sp = await SharedPreferences.getInstance();
    sp.remove(key);
  }
  /// 清理缓存
  static clear() async {
    SharedPreferences sp = await SharedPreferences.getInstance();
    sp.clear();
  }
}