Flutter轻量级数据存储插件flutter_lightweight_store的使用
Flutter轻量级数据存储插件flutter_lightweight_store的使用
A light weight key-value store (SharedPreferences & NSUserdefaults) with saving to separated/customizable xml/plist.
使用
请运行 <code>example/lib/main.dart</code>
来查看更多演示。
/// 标记此实例为静态,这样可以在整个应用程序中访问它
/// 💚 我们将键值对数据保存到名为 `com.your.name.xml` 的文件中(Android)或 `com.your.name.plist` 的文件中(iOS)
FlutterLightweightStoreModule sp = FlutterLightweightStoreModule("com.your.name");
/// 设置器
await sp.setString("String", "Hello world");
await sp.setInt("Int", 10086);
await sp.setDouble("Double", 10086.12306);
await sp.setBoolean("Boolean", true);
/// 获取器
var str = await sp.getString("String");
var int = await sp.getInt("Int");
var double = await sp.getDouble("Double");
var boolean = await sp.getBoolean("Boolean");
print('✅[SP] 设置器与获取器: 字符串 -> $str, 整数 -> $int, 浮点数 -> $double, 布尔值 -> $boolean');
/// 移除
await sp.removeKey('StringKey');
/// 包含检查
bool isContains = await sp.contains('StringKey');
特性和问题
如果您有任何新功能请求或遇到问题,请在 问题追踪器 中提出。
以下是完整的示例代码:
import 'dart:convert';
import 'package:path_provider/path_provider.dart';
import 'package:example/flutter_store_instances.dart';
import 'package:flutter/material.dart';
import 'package:flutter_lightweight_store/flutter_lightweight_store.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
[@override](/user/override)
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
[@override](/user/override)
void initState() {
super.initState();
doStoreTest();
/// 打印应用程序沙盒目录
getApplicationDocumentsDirectory().then((value) {
print('@@@@@@ getApplicationDocumentsDirectory: ${value.absolute.path}');
});
}
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('插件示例应用')),
body: const Center(child: Text('正在运行于:\n')),
),
);
}
void doStoreTest() async {
{
FlutterLightweightStoreModule secure = FlutterStoreInstance.secure;
await secure.setString("String", json.encode({"json": "你🚫好GoodJob"}));
var str = await secure.getString("String");
Map map = str != null ? json.decode(str) : null;
print('@@@@@@ [secure] map: $map');
}
{
FlutterLightweightStoreModule semiSafe = FlutterStoreInstance.semiSafe;
await semiSafe.setString("String", json.encode({"json": "你🚫好GoodJob"}));
var str = await semiSafe.getString("String");
Map map = str != null ? json.decode(str) : null;
print('@@@@@@ [semiSafe] map: $map');
}
{
FlutterLightweightStoreModule user = FlutterStoreInstance.user;
await user.setString("String", json.encode({"json": "你🚫好GoodJob"}));
var str = await user.getString("String");
Map map = str != null ? json.decode(str) : null;
print('@@@@@@ [user] map: $map');
}
{
FlutterLightweightStoreModule config = FlutterStoreInstance.config;
await config.setString("String", json.encode({"json": "你🚫好GoodJob"}));
var str = await config.getString("String");
Map map = str != null ? json.decode(str) : null;
print('@@@@@@ [config] map: $map');
}
{
/// 标记此实例为静态,这样可以在整个应用程序中访问它
FlutterLightweightStoreModule sp = FlutterLightweightStoreModule("com.your.package.name");
await sp.setString("StringKey", "Hello world");
await sp.setInt("IntKey", 10086);
await sp.setDouble("DoubleKey", 10086.12306);
await sp.setBoolean("BooleanKey", true);
var str = await sp.getString("StringKey");
var int = await sp.getInt("IntKey");
var double = await sp.getDouble("DoubleKey");
var boolean = await sp.getBoolean("BooleanKey");
print('@@@@@@ [SP] 设置器与获取器: 字符串 -> $str, 整数 -> $int, 浮点数 -> $double, 布尔值 -> $boolean');
await sp.removeKey('StringKey');
bool isContains = await sp.contains('StringKey');
FlutterLightweightStoreModule common = FlutterStoreInstance.common;
/// 包含检查
String keyContains = '__ok_contains__';
await common.setBoolean(keyContains, true);
bool containsVal1 = await common.contains(keyContains);
await common.removeKey(keyContains);
bool containsVal2 = await common.contains(keyContains);
var containsVal3 = await common.getBoolean(keyContains);
/// 字符串
String keyString = '__ok_string__';
await common.setString(keyString, "Hello 💯🐶你好");
var stringValue1 = await common.getString(keyString);
await common.setString(keyString, "💯💯💯💯💯💯");
var stringValue2 = await common.getString(keyString);
await common.removeKey(keyString);
var stringValue3 = await common.getString(keyString);
/// 整数
String keyInteger = '__ok_int__';
await common.setInt(keyInteger, 100096666666);
var intValue1 = await common.getInt(keyInteger);
await common.setInt(keyInteger, 777777777777);
var intValue2 = await common.getInt(keyInteger);
await common.removeKey(keyInteger);
var intValue3 = await common.getInt(keyInteger);
/// 浮点数
String keyDouble = '__ok_double__';
await common.setDouble(keyDouble, 1009.888);
var doubleValue1 = await common.getDouble(keyDouble);
await common.setDouble(keyDouble, 888888.000999);
var doubleValue2 = await common.getDouble(keyDouble);
await common.removeKey(keyDouble);
var doubleValue3 = await common.getDouble(keyDouble);
/// 布尔值
String keyBoolean = '__ok_boolean__';
await common.setBoolean(keyBoolean, true);
var booleanValue1 = await common.getBoolean(keyBoolean);
await common.setBoolean(keyBoolean, false);
var booleanValue2 = await common.getBoolean(keyBoolean);
await common.removeKey(keyBoolean);
var booleanValue3 = await common.getBoolean(keyBoolean);
print('')
'@@@@@@ [common]'
'\n'
'包含检查: $containsVal1, $containsVal2. 如果删除后是否为空? $containsVal3 (${containsVal3 == null}),'
'\n'
'字符串: $stringValue1, $stringValue2. 如果删除后是否为空? $stringValue3 (${stringValue3 == null})'
'\n'
'整数: $intValue1, $intValue2. 如果删除后是否为空? $intValue3 (${intValue3 == null})'
'\n'
'浮点数: $doubleValue1, $doubleValue2. 如果删除后是否为空? $doubleValue3 (${doubleValue3 == null})'
'\n'
'布尔值: $booleanValue1, $booleanValue2. 如果删除后是否为空? $booleanValue3 (${booleanValue3 == null})'
'\n'
'');
await common.removeKey("__ok_double__");
await common.removeKey("__ok_boolean__");
await common.removeKey("__not_existed_key__");
print('######################## 基础功能测试完成 ########################');
String spName = FlutterStoreInstance.common.module;
Map? result;
result = await FlutterLightweightStorePlatform.methodChannel.invokeMethod<Map>('setString', []);
printResult('错误参数', result);
/// 没有模块或空模块,iOS 中将为 [NSNull null]
result = await FlutterLightweightStorePlatform.methodChannel
.invokeMethod<Map>('setString', {'key': 'key', 'value': 'value'});
printResult('空模块', result);
result = await FlutterLightweightStorePlatform.methodChannel
.invokeMethod<Map>('setString', {'module': null, 'key': 'key', 'value': 'value'});
printResult('空模块', result);
/// 没有键或空键,iOS 中将为 [NSNull null]
result = await FlutterLightweightStorePlatform.methodChannel
.invokeMethod<Map>('setString', {'module': spName, 'value': 'value'});
printResult('空键', result);
result = await FlutterLightweightStorePlatform.methodChannel
.invokeMethod<Map>('setString', {'module': spName, 'key': null, 'value': 'value'});
printResult('空键', result);
/// 没有值或空值,iOS 中将为 [NSNull null]
result = await FlutterLightweightStorePlatform.methodChannel
.invokeMethod<Map>('setString', {'module': spName, 'key': 'key'});
printResult('空值', result);
result = await FlutterLightweightStorePlatform.methodChannel
.invokeMethod<Map>('setString', {'module': spName, 'key': 'key', 'value': null});
printResult('空值', result);
/// 不正确的值
result = await FlutterLightweightStorePlatform.methodChannel
.invokeMethod<Map>('setInt', {'module': spName, 'key': 'key', 'value': 0.223});
printResult('错误的整数值', result);
result = await FlutterLightweightStorePlatform.methodChannel
.invokeMethod<Map>('setInt', {'module': spName, 'key': 'key', 'value': '不是整数'});
printResult('错误的整数类型', result);
print('######################## 测试结果错误完成 ########################');
}
}
void printResult(String flag, Map? map) {
print('>>> $flag 结果: ${jsonEncode(map)}');
}
}
更多关于Flutter轻量级数据存储插件flutter_lightweight_store的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter轻量级数据存储插件flutter_lightweight_store的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,下面是一个关于如何使用Flutter轻量级数据存储插件flutter_lightweight_store
的示例代码。这个插件通常用于在本地存储键值对数据,非常适合轻量级的数据存储需求。
首先,你需要在你的pubspec.yaml
文件中添加这个依赖:
dependencies:
flutter:
sdk: flutter
flutter_lightweight_store: ^x.y.z # 请替换为最新版本号
然后,运行flutter pub get
来安装依赖。
以下是一个完整的示例,演示如何使用flutter_lightweight_store
来存储和检索数据:
import 'package:flutter/material.dart';
import 'package:flutter_lightweight_store/flutter_lightweight_store.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Lightweight Store Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final LightweightStore store = LightweightStore();
String? storedValue;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Flutter Lightweight Store Demo'),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
'Stored Value:',
style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
),
SizedBox(height: 8),
Text(
storedValue ?? 'No value stored yet.',
style: TextStyle(fontSize: 16),
),
SizedBox(height: 24),
ElevatedButton(
onPressed: () async {
// 存储数据
await store.setItem('myKey', 'Hello, Flutter!');
// 检索数据
String? value = await store.getItem('myKey');
// 更新状态
setState(() {
storedValue = value;
});
},
child: Text('Store and Retrieve Value'),
),
],
),
),
);
}
}
在这个示例中,我们做了以下几件事:
- 引入依赖:在
pubspec.yaml
文件中添加flutter_lightweight_store
依赖。 - 创建应用:使用
MaterialApp
创建一个简单的Flutter应用。 - 状态管理:使用
StatefulWidget
来管理应用的状态。 - 存储和检索数据:
- 使用
store.setItem('myKey', 'Hello, Flutter!')
来存储数据。 - 使用
store.getItem('myKey')
来检索数据。 - 使用
setState
来更新UI,显示存储的值。
- 使用
这个示例展示了如何使用flutter_lightweight_store
插件来存储和检索简单的键值对数据。你可以根据需要对这个示例进行扩展和修改,以满足你的具体需求。