本文共 3378 字,大约阅读时间需要 11 分钟。
Flutter作为一款跨平台开发框架,本身并不直接支持数据库操作,但通过SQLite插件,开发者可以为应用添加数据库功能。SQLite插件通过桥接原生系统,实现与设备文件系统的交互,从而为开发者提供基于原生数据库的支持能力。
SQLite插件在以下平台上提供出色的支持:
sqflite_common_ff 插件进行支持。首先需要在项目中添加相关插件:
dependencies: sqflite: ^1.3.0 path: ^2.0.0
导入必要的包:
import 'package:sqflite/sqflite.dart';import 'package:path/path.dart';
打开数据库:SQLite 数据库文件位于设备的默认文件夹中,可通过 getDatabasesPath() 获取路径,并使用 join 方法拼接路径:
var databasesPath = await getDatabasesPath();String path = join(databasesPath, 'my.db');
创建或打开数据库:使用 openDatabase 方法打开或创建数据库,指定版本号和创表回调函数。
Database database = await openDatabase(path, version: 1, onCreate: (Database db, int version) async { await db.execute(''' create table Test ( id INTEGER PRIMARY KEY, name TEXT, value INTEGER, num REAL ) ''');});执行SQL查询:适用于直接操作数据库的任务,可以通过 execute 方法执行 Create、Delete、Update 等 SQL 语句。
处理数据事务:对于增删改查操作,建议使用事务 (transaction) 来提高效率。
关闭数据库:在应用退出时,记得关闭数据库以释放资源:
await database.close();
删除数据库:需要确保应用在删除数据库前已经关闭:
await deleteDatabase(path);
通过 SQL助手生成 Dart 模型类,简化数据库操作:
// 定义表名和字段名final String tableTodo = 'todo';final String columnId = '_id';final String columnTitle = 'title';final String columnDone = 'done';// 生成模型类class Todo { int id; String title; bool done; Map toMap() { var map = {}; map[columnTitle] = title; map[columnDone] = done ? 1 : 0; if (id != null) { map[columnId] = id; } return map; } static Todo fromMap(Map map) { id = map[columnId]; title = map[columnTitle]; done = map[columnDone] == 1; }} 实现增删改查操作,例如使用事务进行批量处理:
class TodoProvider { Database db; Future open(String path) async { db = await openDatabase(path, version: 1, onCreate: (Database db, int version) async { await db.execute(''' create table $tableTodo ( $columnId integer primary key autoincrement, $columnTitle text not null, $columnDone integer not null ) '''); }); } Future insert(Todo todo) async { todo.id = await db.insert(tableTodo, todo.toMap(), conflictAlgorithm: ConflictAlgorithm.replace); return todo; } Future getTodo(int id) async { List 在事务中使用批处理来提高性能:
// 单独批处理final batch = Batch();batch.insert('Test', {'name': 'item'});// 事务中的批处理await database.transaction((txn) async { final batch = txn.batch(); batch.insert('Test', {'name': 'new_item'}); await batch.commit();}); 通过以上方法,开发者可以顺利在 Flutter 应用中使用 SQLite 数据库。
转载地址:http://pexqz.baihongyu.com/