Flutter SQLite数据库管理插件stash_sqlite的使用
Flutter SQLite数据库管理插件stash_sqlite的使用
标题
stash_sqlite
内容
A stash storage extension for sqlite using the drift package
示例代码
import 'package:stash/stash_api.dart';
import 'package:stash_sqlite/stash_sqlite.dart';
class Task {
final int id;
final String title;
final bool completed;
Task({required this.id, required this.title, this.completed = false});
/// Creates a [Task] from json map
factory Task.fromJson(Map<String, dynamic> json) => Task(
id: json['id'] as int,
title: json['title'] as String,
completed: json['completed'] as bool);
/// Creates a json map from a [Task]
Map<String, dynamic> toJson() => <String, dynamic>{
'id': id,
'title': title,
'completed': completed,
};
@override
String toString() {
return 'Task $id, "$title" is ${completed ? "completed" : "not completed"}';
}
}
void main() async {
// Temporary directory
final dirPath = Directory.systemTemp;
// Temporary database file for a shared store
final file = File('${dirPath.path}/stash_sqlite.sdb');
// Creates a store
final store = await newSqliteLocalVaultStore(file: file);
// Creates a vault from the previously created store
final vault = await store.vault<Task>(
name: 'vault',
fromEncodable: (json) => Task.fromJson(json),
eventListenerMode: EventListenerMode.synchronous)
..on<VaultEntryCreatedEvent<Task>>().listen(
(event) => print('Key "${event.entry.key}" added to the vault'));
// Adds a task with key 'task1' to the vault
await vault.put(
'task k', Task(id: 1, title: 'Run vault store example', completed: true));
// Retrieves the value from the vault
print(await vault.get('task k'));
// Closes the vault
vault.close();
}
使用说明
- 添加依赖项到
pubspec.yaml
文件中,替换 x.x.x 为最新版本的 stash_sqlite:dependencies: stash_sqlite: ^x.x.x
- 运行以下命令安装依赖项:
dart pub get
- 开始开发时导入库:
import 'package:stash/stash_api.dart'; import 'package:stash_sqlite/stash_sqlite.dart';
示例代码
-
Vault 示例
import 'dart:io'; import 'package:stash/stash_api.dart'; import 'package:stash_sqlite/stash_sqlite.dart'; class Task { final int id; final String title; final bool completed; Task({required this.id, required this.title, this.completed = false}); /// Creates a [Task] from json map factory Task.fromJson(Map<String, dynamic> json) => Task( id: json['id'] as int, title: json['title'] as String, completed: json['completed'] as bool); /// Creates a json map from a [Task] Map<String, dynamic> toJson() => <String, dynamic>{ 'id': id, 'title': title, 'completed': completed, }; @override String toString() { return 'Task $id, "$title" is ${completed ? "completed" : "not completed"}'; } } void main() async { // Temporary directory final dirPath = Directory.systemTemp; // Temporary database file for a shared store final file = File('${dirPath.path}/stash_sqlite.sdb'); // Creates a store final store = await newSqliteLocalVaultStore(file: file); // Creates a vault from the previously created store final vault = await store.vault<Task>( name: 'vault', fromEncodable: (json) => Task.fromJson(json), eventListenerMode: EventListenerMode.synchronous) ..on<VaultEntryCreatedEvent<Task>>().listen( (event) => print('Key "${event.entry.key}" added to the vault')); // Adds a task with key 'task1' to the vault await vault.put( 'task1', Task(id: 1, title: 'Run vault store example', completed: true)); // Retrieves the value from the vault print(await vault.get('task1')); // Closes the vault vault.close(); }
-
Cache 示例
import 'dart:io'; import 'package:stash/stash_api.dart'; import 'package:stash_sqlite/stash_sqlite.dart'; class Task { final int id; final String title; final bool completed; Task({required this.id, required this.title, this.completed = false}); /// Creates a [Task] from json map factory Task.fromJson(Map<String, dynamic> json) => Task( id: json['id'] as int, title: json['title'] as String, completed: json['completed'] as bool); /// Creates a json map from a [Task] Map<String, dynamic> toJson() => <String, dynamic>{'id': id, 'title': title, 'completed': completed}; @override String toString() { return 'Task $id, "$title" is ${completed ? "completed" : "not completed"}'; } } void main() async { // Temporary directory final dirPath = Directory.systemTemp; // Temporary database file for a shared store final file = File('${dirPath.path}/stash_sqlite.sdb'); // Creates a store final store = await newSqliteLocalCacheStore(file: file); // Creates a cache with a capacity of 10 from the previously created store final cache = await store.cache<Task>( name: 'cache1', fromEncodable: (json) => Task.fromJson(json), maxEntries: 10, eventListenerMode: EventListenerMode.synchronous) ..on<CacheEntryCreatedEvent<Task>>().listen( (event) => print('Key "${event.entry.key}" added to the cache')); // Adds a task with key 'task1' to the cache await cache.put( 'task1', Task(id: 1, title: 'Run cache store example', completed: true)); // Retrieves the value from the cache print(await cache.get('task1')); // Closes the cache cache.close(); }
更多关于Flutter SQLite数据库管理插件stash_sqlite的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
1 回复
更多关于Flutter SQLite数据库管理插件stash_sqlite的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,下面是一个关于如何在Flutter项目中使用stash_sqlite
插件来管理SQLite数据库的示例代码。stash_sqlite
是一个用于Flutter的SQLite数据库管理插件,它提供了高级的数据存储和检索功能。
首先,确保你已经在pubspec.yaml
文件中添加了stash_sqlite
依赖:
dependencies:
flutter:
sdk: flutter
stash: ^x.y.z # 请替换为最新版本号
stash_sqlite: ^x.y.z # 请替换为最新版本号
然后,运行flutter pub get
来安装依赖。
接下来,是一个完整的示例代码,展示了如何使用stash_sqlite
来管理SQLite数据库。
main.dart
import 'package:flutter/material.dart';
import 'package:stash/stash_api.dart';
import 'package:stash_sqlite/stash_sqlite.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter SQLite Example',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
late final Store<int, Map<String, dynamic>> _store;
@override
void initState() {
super.initState();
// 配置SQLite数据库
final StashSQLiteConfig config = StashSQLiteConfig(
databasePath: 'example.db',
databaseName: 'main_db',
tableConfig: TableConfig(
tableName: 'example_table',
),
);
// 创建Store实例
_store = StoreBuilder<int, Map<String, dynamic>>()
..withCodec(Codec.mapCodec<int, Map<String, dynamic>>(
keyCodec: IntCodec(),
valueCodec: MapCodec<String, dynamic>(
keyCodec: StringCodec(),
valueCodec: DynamicCodec(),
),
))
..withBackend(config.backendFactory())
.build();
// 打开数据库连接
_store.open().then((_) {
// 初始化数据库(例如创建表)
_store.writeTxn((txn) async {
await txn.deleteAll(); // 清空表(如果表已存在)
});
});
}
@override
void dispose() {
// 关闭数据库连接
_store.close().then((_) => print('Database closed'));
super.dispose();
}
Future<void> _addItem() async {
final item = {'name': 'Item 1', 'value': 42};
await _store.writeTxn((txn) async {
await txn.put(1, item);
});
print('Item added: $item');
}
Future<void> _retrieveItem() async {
await _store.readTxn((txn) async {
final item = await txn.get(1);
if (item != null) {
print('Item retrieved: $item');
} else {
print('Item not found');
}
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Flutter SQLite Example'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ElevatedButton(
onPressed: _addItem,
child: Text('Add Item'),
),
ElevatedButton(
onPressed: _retrieveItem,
child: Text('Retrieve Item'),
),
],
),
),
);
}
}
解释
- 依赖配置:在
pubspec.yaml
中添加stash
和stash_sqlite
依赖。 - 数据库配置:在
_MyHomePageState
的initState
方法中,配置了SQLite数据库的路径、名称和表配置。 - Store实例创建:使用
StoreBuilder
创建了一个Store
实例,并配置了编解码器和后端(SQLite)。 - 数据库操作:
_addItem
方法:在写事务中向数据库插入一个项目。_retrieveItem
方法:在读事务中从数据库检索项目。
- UI:简单的UI,包含两个按钮,分别用于添加和检索项目。
这个示例展示了如何使用stash_sqlite
进行基本的数据库操作。根据实际需求,你可以进一步扩展这个示例,添加更多的功能和错误处理。