flutter-sqlite

本文详细介绍了如何在Flutter应用中使用SQLite进行数据库操作,包括数据库初始化、增删改查的基本方法。通过示例代码展示了如何创建表、插入数据、获取数据、删除数据和更新数据的操作流程。
摘要由CSDN通过智能技术生成
1.增删改查
2.查询全部数据



#  数据库sqlite
  sqflite: ^1.1.6
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
import 'package:sqflite/sqlite_api.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;

  Todo(this.id, this.title, this.done);

  Map<String, dynamic> toMap() {
    var map = <String, dynamic>{
      columnTitle: title,
      columnDone: done == true ? 1 : 0
    };
    if (id != null) {
      map[columnId] = id;
    }
    return map;
  }

  Todo.fromMap(Map<String, dynamic> map) {
    id = map[columnId];
    title = map[columnTitle];
    done = map[columnDone] == 1;
  }
}

class TodoProvider {
  Database db;

  Future open() async {
   
Flutter 提供了许多用于本地存储的选项,其中 SQLite 是最常用的选项之一。SQLite 是一个轻量级的关系型数据库管理系统,它可以在移动设备中存储和管理数据。 要在 Flutter 中使用 SQLite,您需要使用 sqflite 插件。该插件提供了 SQLite 的 Dart 版本,可以让您从 Flutter 应用程序中轻松地访问和管理 SQLite 数据库。 以下是使用 sqflite 插件的基本步骤: 1. 添加 sqflite 插件依赖到您的 flutter 项目中 在项目的 pubspec.yaml 文件中添加以下代码 ``` dependencies: sqflite: ^1.3.0 ``` 2. 导入 sqflite 在您需要使用 sqflite 的文件中添加以下代码 ``` import 'package:sqflite/sqflite.dart'; ``` 3. 打开数据库 使用以下代码打开数据库并创建一个表: ``` Future<Database> database = openDatabase( // Set the path to the database. join(await getDatabasesPath(), 'example.db'), // When the database is first created, create a table to store dogs. onCreate: (db, version) { // Run the CREATE TABLE statement on the database. return db.execute( "CREATE TABLE dogs(id INTEGER PRIMARY KEY, name TEXT, age INTEGER)", ); }, // Set the version. This executes the onCreate function and provides a // path to perform database upgrades and downgrades. version: 1, ); ``` 4. 插入数据 使用以下代码向数据库中插入数据: ``` // Get a reference to the database. final Database db = await database; // Insert the Dog into the correct table. You might also specify the // `conflictAlgorithm` to use in case the same dog is inserted twice. await db.insert( 'dogs', dog.toMap(), conflictAlgorithm: ConflictAlgorithm.replace, ); ``` 5. 查询数据 使用以下代码从数据库中查询数据: ``` // Query the table for all The Dogs. final List<Map<String, dynamic>> maps = await db.query('dogs'); // Convert the List<Map<String, dynamic> into a List<Dog>. return List.generate(maps.length, (i) { return Dog( id: maps[i]['id'], name: maps[i]['name'], age: maps[i]['age'], ); }); ``` 这些是使用 sqflite 插件进行 SQLite 数据库操作的基本步骤。您可以根据您的需求进行更改和定制。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

IT兔子123

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值