Flutter 中 shared_preferences 的使用
在移动应用开发中,我们经常需要将一些数据持久化保存,以便在应用重启或用户再次使用时能够恢复这些数据。shared_preferences 是 Flutter 提供的一个简单易用的库,专门用于在应用本地存储轻量级的键值对数据。
一. 简介
shared_preferences 是一个用于存储少量数据的轻量级插件,适用于保存简单的键值对数据,如布尔值、整数、字符串和字符串列表等。例如:保存应用的配置参数、用户偏好设置以及一些简单的状态数据。数据可能会异步持久化到磁盘,并且不能保证写入返回后会持久化到磁盘,因此该插件不得用于存储关键数据。
二. 安装shared_preferences
首先,我们需要将 shared_preferences 库添加到项目的 pubspec.yaml 文件中:
dependencies:
flutter:
sdk: flutter
shared_preferences: ^2.3.1
运行 flutter pub get 命令来安装依赖。
三. 基本用法
支持的数据类型为 int 、 double 、 bool 、 String 和 List 。
- 存储数据
final SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setInt('counter', 10);
prefs.setBool('repeat', true);
prefs.setDouble('decimal', 1.5);
prefs.setString('action', 'Start');
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('act