Pub地址:shared_preferences Github地址: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']);
读数据:
// 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 data for the 'counter' key.
final success = await prefs.remove('counter');
三、实战
结合Getx的依赖注入,将SharedPreferences实例异步注入,并在runAPP前初始化。
入口函数:
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Global.init();
runApp(const MyApp());
}
util/global.dart:
class Global {
static Future<void> init() async {
// shared_preferences
await Get.putAsync(() => SharedPreferences.getInstance());
}
}