Skip to content
章节导航

本地存储操作 shared_preferences 的实战应用

什么是 shared_preferences

shared_preferences 是 Flutter 社区开发的一个本地数据存取插件:
https://pub.dev/packages/shared_preferences

  • 简单的,异步的,持久化的 key-value 存储系统;
  • 在 Android 上它是基于 SharedPreferences 的;
  • 在 iOS 上它是基于 NSUserDefaults 的;

如何使用 shared_preferences

首先在 pubspec.yaml 文件中添加

shell
dependencies:
  shared_preferences: ^xxx

记得运行安装哦:flutter packages get

在需要用到的文件中导入

shell
import 'package:shared_preferences/shared_preferences.dart';

存储数据

shell
final prefs = await SharedPreferences.getInstance();
// set value
prefs.setInt('counter', counter);

读取数据

shell
final prefs = await SharedPreferences.getInstance();
// Try reading data from the counter key. If it does not exist, return 0.
final counter = prefs.getInt('counter') ?? 0;}

删除数据

shell
final prefs = await SharedPreferences.getInstance();
prefs.remove('counter');