前言
本文介紹基于 shared_preferences 插件的本地存儲(chǔ)操作。
1. shared_preferences 是什么?
shared_preferences 是一個(gè)本地?cái)?shù)據(jù)存儲(chǔ)的插件:
- 簡(jiǎn)單的,異步的,持久化的 key-value 存儲(chǔ)系統(tǒng);
- 在 Android 上它是基于 SharedPreferences 的;
- 在 iOS 上它是基于 NSUserDefaults 的;
shared_preferences 有哪些常用的API?
2. 如何使用shared_preferences?
步驟一:在 pubspec.yaml 文件中添加:
dependencies:
shared_preferences: ^0.5.3+4
注意:最新的版本號(hào)可以去官網(wǎng)查看,
https://pub.dev/packages/shared_preferences#-installing-tab-
步驟二:運(yùn)行安裝插件:
flutter packages get
步驟三:在需要用到的文件中導(dǎo)入:
import 'package:shared_preferences/shared_preferences.dart';
步驟四:在代碼中使用
void initData() async {
final prefs = await SharedPreferences.getInstance(); //獲取SP的實(shí)例
prefs.setInt('current_num', 999); //存儲(chǔ)數(shù)據(jù)
var currentNum = prefs.getInt('current_num') ?? 0; //讀取數(shù)據(jù),默認(rèn)為0
print('讀取數(shù)據(jù) $currentNum');
prefs.remove('current_num');//刪除數(shù)據(jù)
var delCurrentNum = prefs.getInt('current_num') ?? 0; //讀取數(shù)據(jù),默認(rèn)為0
print('刪除數(shù)據(jù) $delCurrentNum');
}
總結(jié)
我們主要介紹了 shared_preferences 插件的存儲(chǔ)、讀取和刪除數(shù)據(jù),shared_preferences 支持 int、double、bool、String 和 StringList 類型的數(shù)據(jù)存儲(chǔ)。