Flutter单项数据共享插件single_item_shared_prefs的使用
Flutter单项数据共享插件single_item_shared_prefs的使用
SharedPreferences/UserDefaults persistent Storage implementation.
这个包是 single_item_storage
包的一个扩展,并提供了使用 shared_preferences
包和 Dart JSON 转换器(json.encode
和 json.decode
)来存储项目的存储实现。
开始使用
创建一个新的实例时,需要提供 fromMap
和 toMap
项目转换器,itemKey
作为此项目在 SharedPreferences 中的键,以及一个可选的 sharedPreferences
实例。
// 创建一个新的用户存储实例
Storage<User> storage = CachedStorage<User>(SharedPrefsStorage(
itemKey: 'model.user.key', // 设置存储项的键
fromMap: (map) => User.fromMap(map), // 定义从Map转换为对象的方法
toMap: (item) => item.toMap(), // 定义从对象转换为Map的方法
));
// 用户类定义
[@JsonSerializable](/user/JsonSerializable)()
class User {
final String id;
final String email;
factory User.fromMap(Map<String, dynamic> json) => _$UserFromJson(json); // 将Map转换为对象
Map<String, dynamic> toMap() => _$UserToJson(this); // 将对象转换为Map
User(this.id, this.email);
}
如果需要存储不需要转换器的原始值(例如布尔值、双精度浮点数、整数、字符串或字符串列表),可以使用 .primitive
构造函数。
// 存储整数的示例
SharedPrefsStorage<int>.primitive(itemKey: 'cow_counter')
如果省略了 sharedPreferences
参数,则会使用 SharedPreferences.getInstance()
方法获取实例。
注意,SharedPrefsStorage
被包装在 CachedStorage
中以添加内存缓存,从而提高性能。
当定义 to/from map
转换器时,请注意,映射值只能是以下类型之一:数字、布尔值、字符串、null、列表或具有字符串键的映射。这些类型由 dart:convert
包中的 json.encode
和 json.decode
方法定义。
本示例使用 json_serializable
作为映射转换器以方便使用。
完整示例Demo
以下是完整的示例代码,展示了如何使用 single_item_shared_prefs
插件进行数据存储和读取:
import 'package:flutter/material.dart';
import 'package:single_item_storage/single_item_storage.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:json_annotation/json_annotation.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
SharedPreferences prefs = await SharedPreferences.getInstance();
// 创建一个新的用户存储实例
Storage<User> storage = CachedStorage<User>(SharedPrefsStorage(
itemKey: 'model.user.key',
fromMap: (map) => User.fromMap(map),
toMap: (item) => item.toMap(),
sharedPreferences: prefs,
));
// 初始化用户信息
User user = User('1', 'example@example.com');
await storage.setItem(user);
// 读取用户信息
User loadedUser = await storage.getItem();
print('Loaded User ID: ${loadedUser.id}, Email: ${loadedUser.email}');
}
// 用户类定义
[@JsonSerializable](/user/JsonSerializable)()
class User {
final String id;
final String email;
factory User.fromMap(Map<String, dynamic> json) => _$UserFromJson(json);
Map<String, dynamic> toMap() => _$UserToJson(this);
User(this.id, this.email);
}
更多关于Flutter单项数据共享插件single_item_shared_prefs的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter单项数据共享插件single_item_shared_prefs的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,以下是如何在Flutter中使用single_item_shared_prefs
插件来共享单项数据的代码示例。这个插件简化了使用SharedPreferences来存储和检索单个键值对的过程。
首先,确保你的Flutter项目已经添加了single_item_shared_prefs
依赖。在pubspec.yaml
文件中添加以下依赖:
dependencies:
flutter:
sdk: flutter
single_item_shared_prefs: ^最新版本号 # 请替换为实际的最新版本号
然后,运行flutter pub get
来安装依赖。
接下来,你可以在你的Flutter应用中使用这个插件。以下是一个简单的示例,展示如何存储和检索一个单项数据:
import 'package:flutter/material.dart';
import 'package:single_item_shared_prefs/single_item_shared_prefs.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Single Item Shared Preferences Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final SingleItemSharedPreferences _preferences = SingleItemSharedPreferences();
String? _retrievedValue;
@override
void initState() {
super.initState();
// 尝试从SharedPreferences中检索数据
_preferences.getItem('my_key').then((value) {
setState(() {
_retrievedValue = value;
});
});
}
void _storeValue() async {
String newValue = 'Hello, SharedPreferences!';
await _preferences.setItem('my_key', newValue);
// 更新UI以显示新存储的值(在这个例子中,存储后我们不需要立即显示,但这是一个好习惯)
setState(() {
_retrievedValue = newValue; // 实际上,存储后不需要立即设置这个值,因为存储是异步的
});
// 重新检索以模拟从SharedPreferences中读取
_preferences.getItem('my_key').then((value) {
setState(() {
_retrievedValue = value;
});
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Single Item Shared Preferences Demo'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'Retrieved Value: $_retrievedValue',
style: TextStyle(fontSize: 20),
),
SizedBox(height: 20),
ElevatedButton(
onPressed: _storeValue,
child: Text('Store Value'),
),
],
),
),
);
}
}
在这个示例中:
- 我们创建了一个
SingleItemSharedPreferences
实例。 - 在
initState
方法中,我们尝试从SharedPreferences中检索键为'my_key'
的值,并在检索成功后更新UI。 - 我们定义了一个
_storeValue
方法,用于将一个新值存储到键为'my_key'
的位置,并再次检索以更新UI。 - UI包含一个显示检索到的值的
Text
组件和一个用于触发存储操作的ElevatedButton
组件。
这个示例展示了如何使用single_item_shared_prefs
插件来存储和检索单个键值对,并在Flutter应用中动态更新UI。