官方示例:简单调用
// 初始化示例
final SharedPreferences prefs = await SharedPreferences.getInstance();
// 存int
await prefs.setInt('counter', 10);
// 存bool
await prefs.setBool('repeat', true);
// 存double
await prefs.setDouble('decimal', 1.5);
// 存string
await prefs.setString('action', 'Start');
// 存list
await prefs.setStringList('items', <String>['Earth', 'Moon', 'Sun']);// 取值:
final int? counter = prefs.getInt('counter');
final bool? repeat = prefs.getBool('repeat');
final double? decimal = prefs.getDouble('decimal');
final String? action = prefs.getString('action');
final List<String>? items = prefs.getStringList('items');// 删除某个key
prefs.remove('counter')
代码封装
import 'package:shared_preferences/shared_preferences.dart';/// kv离线存储
class Storage {// 单例写法static final Storage _instance = Storage._internal();factory Storage() => _instance;late final SharedPreferences _prefs;Storage._internal();Future<void> init() async {_prefs = await SharedPreferences.getInstance();}Future<bool> setString(String key, String value) async {return await _prefs.setString(key, value);}Future<bool> setBool(String key, bool value) async {return await _prefs.setBool(key, value);}Future<bool> setList(String key, List<String> value) async {return await _prefs.setStringList(key, value);}String getString(String key) {return _prefs.getString(key) ?? '';}bool getBool(String key) {return _prefs.getBool(key) ?? false;}List<String> getList(String key) {return _prefs.getStringList(key) ?? [];}Future<bool> remove(String key) async {return await _prefs.remove(key);}
}
页面调用