Flutter数据库管理插件autosqflite的使用
AutoSqfLite 的使用
AutoSqfLite 是一个为 Flutter 设计的简单、自动化的 SQLite 数据库助手,它能够动态处理表的创建和模式更新。无需手动编写 CREATE TABLE
语句或管理迁移。
特性
- 🚀 自动从 Dart 对象创建表
- 📊 动态模式更新(当新增字段时)
- 🔄 自动在 Dart 和 SQLite 类型之间映射
- 💾 简单的 CRUD 操作
- 🛠 零配置需求
- 🎯 类型安全的操作
- 🔒 数据库密码保护
- 🔄 支持嵌套对象与外键关系
- 📅 自动处理 DateTime
安装
在项目的 pubspec.yaml
文件中添加以下依赖:
dependencies:
autosqflite: ^1.0.0
然后运行 flutter pub get
。
使用
基本设置
// 创建 AutoSqfLite 实例
final db = AutoSqfLite(databaseName: 'my_app');
数据库加密
如果需要加密数据库,可以在创建 AutoSqfLite 实例时提供密码:
final db = AutoSqfLite(
databaseName: 'my_app',
password: 'your_secure_password'
);
重要安全提示:
- 将加密密码安全存储(例如使用
flutter_secure_storage
)。 - 在所有数据库操作中必须始终提供一致的密码。
- 如果密码丢失,数据库将无法恢复。
- 在生产环境中考虑实现适当的密钥管理。
创建模型
class Todo {
final int? id;
final String title;
final bool completed;
final DateTime createdAt;
Todo({
this.id,
required this.title,
required this.completed,
required this.createdAt,
});
// 转换为 Map 用于数据库操作
Map<String, dynamic> toMap() {
return {
'id': id,
'title': title,
'completed': completed ? 1 : 0, // 自动处理布尔值
'createdAt': createdAt.millisecondsSinceEpoch, // 自动处理 DateTime
};
}
// 从 Map 创建对象
factory Todo.fromMap(Map<String, dynamic> map) {
return Todo(
id: map['id'],
title: map['title'],
completed: map['completed'] == 1,
createdAt: DateTime.fromMillisecondsSinceEpoch(map['createdAt']),
);
}
}
CRUD 操作
// 插入数据
await db.insert('todos', todo.toMap());
// 获取所有记录
final todos = await db.getAll('todos');
// 获取单条记录
final todo = await db.get('todos', 1);
// 更新数据
await db.update('todos', todo.toMap(), 1);
// 删除数据
await db.delete('todos', 1);
自动模式更新
AutoSqfLite 自动处理以下内容:
- 当首次插入数据时创建表。
- 当模型发生变化时(如新增字段)自动添加新列。
- 在 Dart 和 SQLite 类型之间自动映射。
// 原始模型
class User {
String name;
int age;
}
// 后续添加新字段 - AutoSqfLite 会自动处理!
class User {
String name;
int age;
String email; // 新字段
bool isActive; // 新字段
}
支持的类型
AutoSqfLite 自动映射 Dart 和 SQLite 类型:
Dart 类型 | SQLite 类型 | 存储格式 |
---|---|---|
int | INTEGER | 直接存储 |
double | REAL | 直接存储 |
String | TEXT | 直接存储 |
bool | INTEGER | 0 或 1 |
DateTime | INTEGER | 自然数毫秒,后缀 _datetime |
DateTime 处理
DateTime 字段会自动:
- 存储为自 Unix 时间戳以来的毫秒数。
- 在数据库中以
_datetime
后缀命名。 - 在检索时自动转换回 DateTime。
- 不需要在模型中进行手动转换。
// 示例:带有 DateTime 的模型
class Event {
final DateTime createdAt;
// AutoSqfLite 自动处理 DateTime 转换
// 字段在数据库中存储为 'createdAt_datetime'
Event({required this.createdAt});
}
示例
以下是一个完整的 Todo 应用程序示例:
class TodoService {
final AutoSqfLite _db;
static const String tableName = 'todos';
TodoService() : _db = AutoSqfLite(databaseName: 'todo_app');
Future<void> addTodo(Todo todo) async {
await _db.insert(tableName, todo.toMap());
}
Future<List<Todo>> getAllTodos() async {
final maps = await _db.getAll(tableName);
return maps.map((map) => Todo.fromMap(map)).toList();
}
Future<void> updateTodo(Todo todo) async {
await _db.update(tableName, todo.toMap(), todo.id!);
}
Future<void> deleteTodo(int id) async {
await _db.delete(tableName, id);
}
}
其他特性
- 自动处理布尔值(转换为 SQLite 的 0/1)。
- DateTime 转换为毫秒数存储。
- 非空安全操作。
- 自动检查表是否存在。
贡献
欢迎贡献!请随时提交 Pull Request。对于重大更改,请先打开一个问题讨论你想要进行的更改。
许可证
该项目基于 MIT 许可证发布 - 详见 LICENSE 文件。
致谢
- 基于出色的 sqflite_sqlcipher 包构建。
- 受到简化 Flutter 数据库操作的需求启发。
支持
如果你觉得这个包有用,请在 pub.dev 上点赞并在 GitHub 仓库 上给我们加星!
DateTime 和嵌套对象
AutoSqfLite 提供了增强的 DateTime 字段和嵌套对象支持:
// 示例:带有 DateTime 和嵌套对象
class Order {
final DateTime createdAt;
final DateTime updatedAt;
Order({
required this.createdAt,
required this.updatedAt,
});
// 转换为 Map 用于数据库操作
Map<String, dynamic> toMap() {
return {
'createdAt': createdAt.millisecondsSinceEpoch,
'updatedAt': updatedAt.millisecondsSinceEpoch,
};
}
// 从 Map 创建对象
factory Order.fromMap(Map<String, dynamic> map) {
return Order(
createdAt: DateTime.fromMillisecondsSinceEpoch(map['createdAt']),
updatedAt: DateTime.fromMillisecondsSinceEpoch(map['updatedAt']),
);
}
}
更多关于Flutter数据库管理插件autosqflite的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter数据库管理插件autosqflite的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
auto_sqflite
是一个基于 sqflite
的 Flutter 插件,它简化了 SQLite 数据库的操作,提供了自动化的 CRUD(创建、读取、更新、删除)功能。通过使用 auto_sqflite
,你可以更轻松地管理 SQLite 数据库,而不需要编写大量的 SQL 语句。
安装 auto_sqflite
首先,你需要在 pubspec.yaml
文件中添加 auto_sqflite
依赖:
dependencies:
flutter:
sdk: flutter
auto_sqflite: ^1.0.0
然后运行 flutter pub get
来安装依赖。
使用 auto_sqflite
1. 创建数据库和表
首先,你需要定义一个模型类,并使用 [@Table](/user/Table)
注解来标记它。auto_sqflite
会根据这个类自动创建数据库表。
import 'package:auto_sqflite/auto_sqflite.dart';
[@Table](/user/Table)(name: 'users')
class User {
[@PrimaryKey](/user/PrimaryKey)(autoGenerate: true)
int? id;
[@Column](/user/Column)(name: 'name')
String? name;
[@Column](/user/Column)(name: 'age')
int? age;
User({this.id, this.name, this.age});
}
2. 初始化数据库
在应用启动时,你需要初始化数据库。你可以使用 AutoSqflite
类来管理数据库连接。
import 'package:auto_sqflite/auto_sqflite.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
// 初始化数据库
await AutoSqflite().initializeDatabase(
databaseName: 'my_database.db',
version: 1,
tables: [User],
);
runApp(MyApp());
}
3. 插入数据
你可以使用 AutoSqflite
的 insert
方法来插入数据。
void insertUser() async {
var user = User(name: 'John Doe', age: 30);
await AutoSqflite().insert(user);
}
4. 查询数据
你可以使用 AutoSqflite
的 query
方法来查询数据。
void queryUsers() async {
List<User> users = await AutoSqflite().query(User);
users.forEach((user) {
print('User: ${user.name}, Age: ${user.age}');
});
}
5. 更新数据
你可以使用 AutoSqflite
的 update
方法来更新数据。
void updateUser() async {
var user = User(id: 1, name: 'John Doe', age: 31);
await AutoSqflite().update(user);
}
6. 删除数据
你可以使用 AutoSqflite
的 delete
方法来删除数据。
void deleteUser() async {
await AutoSqflite().delete(User, where: 'id = ?', whereArgs: [1]);
}
完整示例
以下是一个完整的示例,展示了如何使用 auto_sqflite
进行数据库操作。
import 'package:flutter/material.dart';
import 'package:auto_sqflite/auto_sqflite.dart';
[@Table](/user/Table)(name: 'users')
class User {
[@PrimaryKey](/user/PrimaryKey)(autoGenerate: true)
int? id;
[@Column](/user/Column)(name: 'name')
String? name;
[@Column](/user/Column)(name: 'age')
int? age;
User({this.id, this.name, this.age});
}
void main() async {
WidgetsFlutterBinding.ensureInitialized();
// 初始化数据库
await AutoSqflite().initializeDatabase(
databaseName: 'my_database.db',
version: 1,
tables: [User],
);
runApp(MyApp());
}
class MyApp extends StatelessWidget {
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text('AutoSqflite Example')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(
onPressed: insertUser,
child: Text('Insert User'),
),
ElevatedButton(
onPressed: queryUsers,
child: Text('Query Users'),
),
ElevatedButton(
onPressed: updateUser,
child: Text('Update User'),
),
ElevatedButton(
onPressed: deleteUser,
child: Text('Delete User'),
),
],
),
),
),
);
}
}
void insertUser() async {
var user = User(name: 'John Doe', age: 30);
await AutoSqflite().insert(user);
}
void queryUsers() async {
List<User> users = await AutoSqflite().query(User);
users.forEach((user) {
print('User: ${user.name}, Age: ${user.age}');
});
}
void updateUser() async {
var user = User(id: 1, name: 'John Doe', age: 31);
await AutoSqflite().update(user);
}
void deleteUser() async {
await AutoSqflite().delete(User, where: 'id = ?', whereArgs: [1]);
}