返回

Flutter 中轻松搞定 SQLite 数据库,小白也能看懂!

前端

前言

在 Flutter 中使用 SQLite 数据库非常简单,只需要几个步骤即可。本教程将从头开始教你如何使用 SQLite 数据库,即使你是完全的小白,也能轻松上手。

准备工作

在开始之前,你需要确保已经安装了 Flutter SDK 并配置好了开发环境。你还可以先查看官方的 sqlite 教程,它写得相当不错,比其他中文版的文章教程好多了。

新建项目

首先,创建一个新的 Flutter 项目。你可以使用 Flutter CLI 命令行工具或者 Android Studio/IntelliJ IDEA 等 IDE。

添加依赖

接下来,你需要在你的项目中添加 SQLite 依赖。在你的 pubspec.yaml 文件中添加以下依赖:

dependencies:
  sqflite: ^2.2.0+2

创建数据库

现在,你可以创建一个 SQLite 数据库。在你的代码中,使用以下代码创建数据库:

import 'dart:async';
import 'package:sqflite/sqflite.dart';

Future<Database> createDatabase() async {
  // Get the application documents directory.
  final documentsDirectory = await getApplicationDocumentsDirectory();

  // Construct the path to the database file.
  final path = join(documentsDirectory.path, 'database.db');

  // Open the database.
  final database = await openDatabase(
    path,
    version: 1,
    onCreate: (Database db, int version) async {
      // Create the table.
      await db.execute(
        'CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)',
      );
    },
  );

  return database;
}

插入数据

接下来,你可以向数据库中插入数据。使用以下代码插入数据:

Future<void> insertData() async {
  // Get the database.
  final database = await createDatabase();

  // Insert the data.
  await database.insert(
    'users',
    {'name': 'John Doe', 'age': 30},
  );

  // Close the database.
  await database.close();
}

查询数据

现在,你可以查询数据库中的数据。使用以下代码查询数据:

Future<List<Map<String, dynamic>>> queryData() async {
  // Get the database.
  final database = await createDatabase();

  // Query the data.
  final result = await database.query('users');

  // Close the database.
  await database.close();

  return result;
}

小结

以上就是 Flutter 中使用 SQLite 数据库的基本步骤。现在,你已经学会了如何创建数据库、插入数据和查询数据。你可以根据需要对代码进行修改,以满足你的具体需求。