Flutter本地存储插件simple_storage的使用
Flutter本地存储插件simple_storage的使用
特性
- Collections: 将数据组织到命名集合中,类似于关系数据库中的表。
- 键值存储: 以键值对形式存储数据,允许灵活的数据结构。
- 并发控制: 使用
synchronized
库实现线程安全的数据访问,并通过锁来管理。 - 索引: 支持指定字段的内存索引,以加快查找速度。
- 分页: 使用
limit
和offset
来分批获取数据,提高性能。 - 事务: 通过事务范围内的多个更改来确保原子操作。
- TTL(生存时间): 允许设置数据过期时间,适合用于缓存和临时数据管理。
- 纯 Dart: 完全用 Dart 编写,易于理解和修改。
- 文件持久化: 将所有数据存储在 JSON 文件中,具有清晰且定义明确的结构。
开始使用
添加依赖
在pubspec.yaml
文件中添加 simple_storage
依赖:
flutter pub add simple_storage
导入库
在 Dart 文件中导入 simple_storage
库:
import 'package:simple_storage/simple_storage.dart';
创建数据库实例
创建一个数据库实例并指定存储路径:
final db = Database('./my_database'); // 指定存储路径
构造函数参数指定了数据库文件将被存储的目录。
创建或访问集合
创建或访问一个集合,如果该集合不存在则会自动创建:
final users = await db.collection('users', indexes: ['age', 'name']);
第一个参数是集合名称。如果集合不存在,它将被创建。可选的 indexes
参数是一个包含应被索引的属性名的字符串列表。索引可以加速基于这些属性的查找,但过度使用可能会减慢插入速度。
存储数据(可选TTL)
使用 put
方法存储数据,同时可以设置 ttl
参数来指定数据的生存时间:
await collection.put('int', 10); // 存储整数
await collection.put('double', 10.5); // 存储浮点数
await collection.put('bool', true); // 存储布尔值
await collection.put('string', 'hello world'); // 存储字符串
await collection.put('map', {"key": "value"}); // 存储映射
获取数据
使用 get
方法通过键获取数据:
var intValue = await collection.get(key: 'int');
var doubleValue = await collection.get(key: 'double');
var boolValue = await collection.get(key: 'bool');
var stringValue = await collection.get(key: 'string');
var mapValue = await collection.get(key: 'map');
如果键对应的值是已索引的字段,还应提供相应的值来过滤结果。
分页获取数据
使用 getAll
方法结合 limit
和 offset
参数分页获取数据:
var listAllValues = await collection.getAll(limit: 5, offset: 0);
limit
参数指定返回的最大数据量,offset
参数指定页面的起始位置。
在事务中执行操作
使用事务确保一组操作在一次提交或回滚中完成:
final transaction = await collection.startTransaction();
await transaction.put('key', 'value');
await transaction.commit();
错误处理
捕获并处理特定的异常:
try {
// 数据库操作
} on DatabaseCreateException catch (e) {
debugPrint("Database creation failed ${e.toString()}");
} on CollectionLoadException catch (e) {
debugPrint('Error loading collection: ${e.toString()}');
} on CollectionSaveException catch (e) {
debugPrint('Error saving collection: ${e.toString()}');
} on CollectionNotFoundException catch (e) {
debugPrint("Collection not found: ${e.toString()}");
} catch (e) {
debugPrint('An unexpected error occurred: $e');
}
核心类
Database
- 管理存储路径和对集合的访问。
collection
方法返回特定名称的集合。
Collection
- 表示一个数据集合,存储键值对数据,可选的
ttl
。 - 提供
put
,get
,getAll
,delete
方法来管理数据。 - 管理索引以加快基于指定字段的查找。
- 管理分页以分批获取数据。
- 提供事务功能,使用
startTransaction
方法。
Transaction
- 管理事务状态,使用锁以原子方式执行一系列操作。
- 提供
put
,delete
,commit
,rollback
方法来管理事务。
示例代码
以下是一个完整的示例代码,展示了如何使用 simple_storage
插件进行基本的操作:
import 'package:flutter/material.dart';
import 'package:simple_storage/simple_storage.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
runApp(const MainApp());
try {
final dbPath = './database';
final db = Database(dbPath);
final collection = await db.collection('test');
await collection.put('int', 10);
await collection.put('double', 10.5);
await collection.put('bool', true);
await collection.put('string', 'hello world');
await collection.put('map', {"key": "value"});
var intValue = await collection.get(key: 'int');
var doubleValue = await collection.get(key: 'double');
var boolValue = await collection.get(key: 'bool');
var stringValue = await collection.get(key: 'string');
var mapValue = await collection.get(key: 'map');
debugPrint('int: $intValue type: ${intValue.runtimeType}');
debugPrint('double: $doubleValue type: ${doubleValue.runtimeType}');
debugPrint('bool: $boolValue type: ${boolValue.runtimeType}');
debugPrint('string: $stringValue type: ${stringValue.runtimeType}');
debugPrint('map: $mapValue type: ${mapValue.runtimeType}');
var listAllValues = await collection.getAll();
debugPrint(
'listAllValues: $listAllValues type: ${listAllValues.runtimeType}');
} on DatabaseCreateException catch (e) {
debugPrint("Database creation failed ${e.toString()}");
} on CollectionLoadException catch (e) {
debugPrint('Error loading collection: ${e.toString()}');
} on CollectionSaveException catch (e) {
debugPrint('Error saving collection: ${e.toString()}');
} on CollectionNotFoundException catch (e) {
debugPrint("Collection not found: ${e.toString()}");
} catch (e) {
debugPrint('An unexpected error occurred: $e');
}
}
class MainApp extends StatelessWidget {
const MainApp({super.key});
[@override](/user/override)
Widget build(BuildContext context) {
return const MaterialApp(
home: Scaffold(
body: Center(
child: Text('Hello World!'),
),
),
);
}
}
更多关于Flutter本地存储插件simple_storage的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter本地存储插件simple_storage的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,以下是一个关于如何使用Flutter本地存储插件simple_storage
的示例代码。这个插件允许你在Flutter应用中轻松地进行本地存储和检索数据。
首先,确保你已经在pubspec.yaml
文件中添加了simple_storage
依赖:
dependencies:
flutter:
sdk: flutter
simple_storage: ^4.0.0 # 请注意版本号,根据实际需要调整
然后,运行flutter pub get
来安装依赖。
接下来,你可以按照以下步骤在你的Flutter应用中使用simple_storage
。
示例代码
- 导入插件
在你的Dart文件中导入simple_storage
插件:
import 'package:simple_storage/simple_storage.dart';
- 初始化存储
在应用的入口文件(通常是main.dart
)中初始化存储:
void main() async {
WidgetsFlutterBinding.ensureInitialized();
// 初始化存储
final storage = await SimpleStorage.init();
runApp(MyApp(storage: storage));
}
- 使用存储
在你的应用中,你可以使用存储来保存和读取数据。例如,在一个简单的页面中:
import 'package:flutter/material.dart';
import 'package:simple_storage/simple_storage.dart';
class MyApp extends StatelessWidget {
final SimpleStorage storage;
MyApp({required this.storage});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: MyHomePage(storage: storage),
);
}
}
class MyHomePage extends StatefulWidget {
final SimpleStorage storage;
MyHomePage({required this.storage});
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final TextEditingController _controller = TextEditingController();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Simple Storage Example'),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
TextField(
controller: _controller,
decoration: InputDecoration(labelText: 'Enter some text'),
),
SizedBox(height: 16),
ElevatedButton(
onPressed: () async {
// 保存数据
await widget.storage.write(key: 'myText', value: _controller.text);
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('Data saved')));
},
child: Text('Save'),
),
SizedBox(height: 16),
ElevatedButton(
onPressed: () async {
// 读取数据
String? readValue = await widget.storage.read(key: 'myText');
setState(() {
_controller.text = readValue ?? '';
});
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('Data read')));
},
child: Text('Read'),
),
],
),
),
);
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
}
解释
-
初始化存储:在
main
函数中,我们确保Flutter绑定已经初始化,然后初始化SimpleStorage
实例。 -
传递存储实例:我们将
SimpleStorage
实例传递给应用的其他部分,以便在整个应用中访问存储。 -
保存数据:通过调用
widget.storage.write(key: 'myText', value: _controller.text)
来保存文本数据。 -
读取数据:通过调用
widget.storage.read(key: 'myText')
来读取之前保存的数据,并更新UI。
这个示例展示了如何使用simple_storage
插件在Flutter应用中实现基本的本地存储功能。你可以根据需要扩展和修改这个示例,以适应你的应用需求。