1. Introduction to shared_preferences
There is no local storage mechanism inside Flutter, and we are officially recommended to use it shared_preferences
. This plugin is a local data access plugin provided by Flutter.
shared_preferences is developed based on different mechanisms on different platforms, such as the development based on SharedPreferences in the Android platform, and the development based on NSUserDefaults in the iOS platform;
limit:
- Accessing local files is a time-consuming operation, so accessing shared_preferences storage is an asynchronous operation;
- Encapsulate 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 it will persist to disk after the write returns, so this plugin cannot be used to store critical data.
2. Add and use
1. Add dependencies to pubspec.yaml
dependencies:
shared_preferences: 2.0.15 #本地存储插件
2. Import in the file
import 'package:shared_preferences/shared_preferences.dart';
3. Supported data types
int, double, bool, String , List。
4. Basic code
- data input
saveUserName(String name) async {
var user = await SharedPreferences.getInstance(); //初始化
user .setString("name", name);
}
user .setInt("age", 0);
user .setBool("sex", true);
user .setDouble("height", 10.1);
user .setStringList("address", <String>["", ""]);
- read data
getUserName(BuildContext context) async {
var user = await SharedPreferences.getInstance(); //初始化
String? name = user .getString("name");
}
int? age = user .getInt("age");
bool? sex = user .getBool("sex");
double? height = user .getDouble("height");
List<String>? address = user .getStringList("address");
- delete data
delete a data
removeLogin() async {
var user= await SharedPreferences.getInstance(); //初始化
user.remove("name");
}
delete all data
user.clear();
- Get all keys
var user = await SharedPreferences.getInstance();
var keys = user.getKeys();
- Does the key exist?
var user = await SharedPreferences.getInstance();
var result = user.containsKey("name");