博客
关于我
Flutter数据库的使用
阅读量:687 次
发布时间:2019-03-16

本文共 3378 字,大约阅读时间需要 11 分钟。

Flutter中的SQLite支持说明

Flutter作为一款跨平台开发框架,本身并不直接支持数据库操作,但通过SQLite插件,开发者可以为应用添加数据库功能。SQLite插件通过桥接原生系统,实现与设备文件系统的交互,从而为开发者提供基于原生数据库的支持能力。


1. 支持平台

SQLite插件在以下平台上提供出色的支持:

  • iOS、Android:支持 SQLite 数据库操作。
  • macOS:支持 SQLite 数据库功能。
  • Linux、Windows:建议使用 sqflite_common_ff 插件进行支持。
  • Web平台:不支持 SQLite 数据库操作。

2. 数据库操作特点

  • 后台执行:数据库操作应放置在后台工作 thread 中进行。
  • 事务处理:尽量使用事务(transaction)来提高效率。
  • 批处理:可以通过批处理方式减少与原生系统的频繁交互。

3. 简单使用指南

3.1 添加依赖

首先需要在项目中添加相关插件:

dependencies:  sqflite: ^1.3.0  path: ^2.0.0
3.2 使用步骤
  • 导入必要的包

    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);

  • 4. SQL助手的使用

    4.1 创建模型类

    通过 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; }}
    4.2 数据操作

    实现增删改查操作,例如使用事务进行批量处理:

    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
    > maps = await db.query( tableTodo, columns: [columnId, columnDone, columnTitle], where: '$columnId = ?', whereArgs: [id] ); if (maps.isNotEmpty) { return Todo.fromMap(maps.first); } return null; } Future
    delete(int id) async { return await db.delete(tableTodo, where: '$columnId = ?', whereArgs: [id]); } Future
    update(Todo todo) async { return await db.update( tableTodo, todo.toMap(), where: '$columnId = ?', whereArgs: [todo.id] ); } Future
    close() async => db.close();}

    5. 批处理

    在事务中使用批处理来提高性能:

    // 单独批处理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();});

    6. 注意事项

    • 避免使用关键字:表名和列名不可用 SQLite 关键字。
    • 存储类型限制:DateTime 类型建议存储为 String 或 int,bool 也需转换为 int。

    通过以上方法,开发者可以顺利在 Flutter 应用中使用 SQLite 数据库。

    转载地址:http://pexqz.baihongyu.com/

    你可能感兴趣的文章
    QVGA/HVGA/WVGA/FWVGA分辨率屏含义及大小//Android虚拟机分辨率
    查看>>
    pipreqs : 无法将“pipreqs”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。请检查名称的拼写,如果包括路径,请确保路径 正确,然后再试一次。
    查看>>
    pipy国内镜像的网址
    查看>>
    quiver绘制python语言
    查看>>
    pip下载缓慢
    查看>>
    PIP使用SSH从BitBucket安装自定义软件包,无需输入SSH密码
    查看>>
    pip命令提示unknow or unsupported command install解决方法
    查看>>
    pip在安装模块时提示Read timed out
    查看>>
    pip更换源
    查看>>
    SpringBoot之Banner源码深度分解
    查看>>
    Pix2Pix如何工作?
    查看>>
    QuickBI助你成为分析师——搞定数据源
    查看>>
    pkl来存储python字典
    查看>>
    quick sort | 快速排序 C++ 实现
    查看>>
    pkpmbs 建设工程质量监督系统 Ajax_operaFile.aspx 文件读取漏洞复现
    查看>>
    pkpmbs 建设工程质量监督系统 文件上传漏洞复现
    查看>>
    pku 2400 Supervisor, Supervisee KM求最小权匹配+DFS回溯解集
    查看>>