博客
关于我
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/

    你可能感兴趣的文章
    NSSet集合 无序的 不能重复的
    查看>>
    nullnullHuge Pages
    查看>>
    Numpy如何使用np.umprod重写range函数中i的python
    查看>>
    oauth2-shiro 添加 redis 实现版本
    查看>>
    OAuth2.0_JWT令牌-生成令牌和校验令牌_Spring Security OAuth2.0认证授权---springcloud工作笔记148
    查看>>
    OAuth2.0_JWT令牌介绍_Spring Security OAuth2.0认证授权---springcloud工作笔记147
    查看>>
    OAuth2.0_介绍_Spring Security OAuth2.0认证授权---springcloud工作笔记137
    查看>>
    OAuth2.0_完善环境配置_把资源微服务客户端信息_授权码存入到数据库_Spring Security OAuth2.0认证授权---springcloud工作笔记149
    查看>>
    OAuth2.0_授权服务配置_Spring Security OAuth2.0认证授权---springcloud工作笔记140
    查看>>
    OAuth2.0_授权服务配置_密码模式及其他模式_Spring Security OAuth2.0认证授权---springcloud工作笔记145
    查看>>
    OAuth2.0_授权服务配置_资源服务测试_Spring Security OAuth2.0认证授权---springcloud工作笔记146
    查看>>
    OAuth2.0_环境搭建_Spring Security OAuth2.0认证授权---springcloud工作笔记139
    查看>>
    OA系统多少钱?OA办公系统中的价格选型
    查看>>
    object detection错误之Could not create cudnn handle: CUDNN_STATUS_INTERNAL_ERROR
    查看>>
    Object Oriented Programming in JavaScript
    查看>>
    OBJECTIVE C (XCODE) 绘图功能简介(转载)
    查看>>
    Objective-C——判断对象等同性
    查看>>
    Objective-C之成魔之路【7-类、对象和方法】
    查看>>
    Objective-C享元模式(Flyweight)
    查看>>
    Objective-C以递归的方式实现二叉搜索树算法(附完整源码)
    查看>>