flutter 开发中常用的数据持久化插件shared_preferences,用来存储不是特别重要的数据
插件地址:shared_preferences | Flutter Package (pub.dev)
支持的平台和数据类型:
截屏2022-07-29 11.02.30.png官方介绍中解释了为什么 不建议用 shared_preferences存储关键数据:
Wraps platform-specific persistent storage for simple data (NSUserDefaults on iOS and macOS, SharedPreferences on Android, etc.). Data may be persisted to disk asynchronously, and there is no guarantee that writes will be persisted to disk after returning, so this plugin must not be used for storing critical data.
为简单数据包装特定于平台的持久存储(iOS 和 macOS 上的 NSUserDefaults,Android 上的 SharedPreferences 等)。数据可能会异步持久化到磁盘,并且不能保证写入返回后会持久化到磁盘,所以这个插件一定不能用于存储关键数据。
官方给出的例子
Write data
// Obtain shared preferences.
final 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.
final success = await prefs.remove('counter');
实际开发中和官方例子中的用法区别不大,可能会封装出一个工具类实现一些项目中的特定需求,根据需求自由发挥
网友评论