Flutter数据库操作插件sqflite_adapter的使用

发布于 1周前 作者 zlyuanteng 来自 Flutter

Flutter数据库操作插件sqflite_adapter的使用

1. 开始使用

首先,在你的Flutter项目中添加sqflite_adapter依赖。打开终端并运行以下命令:

flutter pub add sqflite_adapter

2. 使用方法

创建表提供者

通过继承TableProvider类并实现抽象方法来创建一个表提供者。TableProvider类提供了一种简单的方式来创建表结构并在表上执行CRUD(创建、读取、更新、删除)操作。

class TodoTableProvider extends TableProvider<TodoModel> {
  final String tableName = 'todo';
  final String id = 'id';
  final String title = 'title';
  final String isDone = 'isDone';

  [@override](/user/override)
  Future<void> insert(TodoModel model) {
    return db.insert(tableName, model.toMap());
  }

  [@override](/user/override)
  Future<void> createTable() {
    return db.execute('CREATE TABLE $tableName ($id TEXT PRIMARY KEY, $title TEXT, $isDone INTEGER)');
  }

  [@override](/user/override)
  Future<void> clear() {
    return db.delete(tableName);
  }

  [@override](/user/override)
  Future<void> update(TodoModel model) {
    return db.update(tableName, model.toMap(), where: '$id = ?', whereArgs: [model.id]);
  }

  // 自定义查询方法,获取所有数据
  Future<List<TodoModel>> getAll() async {
    final List<Map<String, dynamic>> maps = await db.query(tableName);
    return List.generate(maps.length, (i) {
      return TodoModel.fromMap(maps[i]);
    });
  }
}
初始化数据库服务

创建一个新的SQLService实例,并将表提供者传递给tables参数。然后调用initialize方法来初始化数据库。

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  SQLService sqlService = await SQLService(
      tables: [
        TodoTableProvider()
      ],
      databaseName: 'todo.db'
  ).initialize();
  runApp(MyApp(sqlService: sqlService));
}

3. 示例用法

你可以通过sqlService来插入、更新、删除和查询数据。以下是几个示例:

  • 插入一条记录:
sqlService.of<TodoTableProvider>().insert(TodoModel(id: '1', title: 'Buy milk', isDone: false));
// 或者
sqlService.insert<TodoModel>(TodoModel(id: '1', title: 'Buy milk', isDone: false));
  • 获取所有记录:
sqlService.of<TodoTableProvider>().getAll();

4. 完整示例代码

以下是一个完整的示例代码,展示了如何在Flutter应用中使用sqflite_adapter来管理待办事项列表(Todo List)。

import 'package:flutter/material.dart';
import 'package:sqflite_adapter/sqflite_adapter.dart';
import 'package:uuid/uuid.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  SQLService sqlService =
      await SQLService(tables: [TodoTableProvider()], databaseName: 'todo.db')
          .initialize();
  runApp(MyApp(sqlService: sqlService));
}

class MyApp extends StatelessWidget {
  final SQLService sqlService;
  const MyApp({super.key, required this.sqlService});

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.blue),
        useMaterial3: true,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page', sqlService: sqlService),
    );
  }
}

class MyHomePage extends StatefulWidget {
  final SQLService sqlService;
  const MyHomePage({super.key, required this.title, required this.sqlService});
  final String title;

  [@override](/user/override)
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final TextEditingController _controller = TextEditingController();
  List<TodoModel> todos = [];

  _create() {
    final TodoModel todo = TodoModel(
      title: _controller.text,
      id: const Uuid().v4(),
    );
    widget.sqlService.insert<TodoModel>(todo).then((value) {
      setState(() {
        todos.add(todo);
        _controller.clear();
      });
    });
  }

  _toggle(TodoModel todo) => (bool? value) {
        setState(() {
          final newTodo = todo.copyWith(isDone: value);
          todos = todos.map((e) {
            if (e.id == todo.id) {
              return newTodo;
            }
            return e;
          }).toList();
          widget.sqlService.update<TodoModel>(newTodo);
        });
      };

  _clear() {
    setState(() {
      widget.sqlService.clear();
      todos.clear();
    });
  }

  [@override](/user/override)
  void initState() {
    widget.sqlService.of<TodoTableProvider>().getAll().then((value) {
      setState(() {
        todos = value;
      });
    });
    super.initState();
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(widget.title),
      ),
      body: Column(
        children: [
          ...todos.map((todo) {
            return ListTile(
              title: Text(todo.title),
              trailing: Checkbox(value: todo.isDone, onChanged: _toggle(todo)),
            );
          }),
          TextField(
            controller: _controller,
          ),
          ElevatedButton(
            onPressed: _create,
            child: const Text('Create'),
          ),
          ElevatedButton(
            style: ElevatedButton.styleFrom(
              backgroundColor: Colors.red,
            ),
            onPressed: _clear,
            child: const Text('Clear all'),
          ),
        ],
      ),
    );
  }
}

class TodoModel {
  final String id;
  final String title;
  final bool isDone;

  TodoModel({required this.id, required this.title, this.isDone = false});

  Map<String, dynamic> toMap() {
    return {
      'id': id,
      'title': title,
      'isDone': isDone ? 1 : 0,
    };
  }

  factory TodoModel.fromMap(Map<String, dynamic> map) {
    return TodoModel(
      id: map['id'],
      title: map['title'],
      isDone: map['isDone'] == 1,
    );
  }

  TodoModel copyWith({String? id, String? title, bool? isDone}) {
    return TodoModel(
      id: id ?? this.id,
      title: title ?? this.title,
      isDone: isDone ?? this.isDone,
    );
  }
}

class TodoTableProvider extends TableProvider<TodoModel> {
  final String tableName = 'todo';
  final String id = 'id';
  final String title = 'title';
  final String isDone = 'isDone';

  [@override](/user/override)
  Future<void> insert(TodoModel model) {
    return db.insert(tableName, model.toMap());
  }

  [@override](/user/override)
  Future<void> createTable() {
    return db.execute(
        'CREATE TABLE $tableName ($id TEXT PRIMARY KEY, $title TEXT, $isDone INTEGER)');
  }

  [@override](/user/override)
  Future<void> clear() {
    return db.delete(tableName);
  }

  [@override](/user/override)
  Future<void> update(TodoModel model) {
    return db.update(tableName, model.toMap(),
        where: '$id = ?', whereArgs: [model.id]);
  }

  Future<List<TodoModel>> getAll() async {
    final List<Map<String, dynamic>> maps = await db.query(tableName);
    return List.generate(maps.length, (i) {
      return TodoModel.fromMap(maps[i]);
    });
  }
}

更多关于Flutter数据库操作插件sqflite_adapter的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter数据库操作插件sqflite_adapter的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是一个关于如何使用 sqflite_adapter 插件在 Flutter 中进行数据库操作的示例代码。请注意,sqflite_adapter 并不是一个官方的 Flutter 插件,你可能指的是与 sqflite 相关的适配器或者包装器。通常,Flutter 社区使用 sqflite 插件来与 SQLite 数据库进行交互。下面是一个使用 sqflite 插件的示例,展示了如何创建数据库、创建表、插入数据、查询数据以及更新数据。

首先,确保在你的 pubspec.yaml 文件中添加 sqflite 依赖:

dependencies:
  flutter:
    sdk: flutter
  sqflite: ^2.0.2  # 确保使用最新版本

然后,运行 flutter pub get 来获取依赖。

接下来,创建一个 Dart 文件(例如 database_helper.dart)来封装数据库操作:

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

class DatabaseHelper {
  static DatabaseHelper _instance = DatabaseHelper._internal();

  factory DatabaseHelper() => _instance;

  DatabaseHelper._internal();

  Database? _database;

  Future<Database> get database async {
    if (_database != null) return _database!;

    _database = await initDb();
    return _database!;
  }

  Future<Database> initDb() async {
    Directory documentsDirectory = await getApplicationDocumentsDirectory();
    String path = join(documentsDirectory.path, 'my_database.db');

    return await openDatabase(path, version: 1, onCreate: _createTable);
  }

  Future _createTable(Database db, int version) async {
    await db.execute('''
      CREATE TABLE users (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        name TEXT NOT NULL,
        age INTEGER NOT NULL
      )
    ''');
  }

  Future<void> insertUser(String name, int age) async {
    final Database db = await database;
    await db.insert('users', {'name': name, 'age': age});
  }

  Future<List<Map<String, dynamic>>> getUsers() async {
    final Database db = await database;
    return await db.query('users');
  }

  Future<void> updateUser(int id, String name, int age) async {
    final Database db = await database;
    await db.update('users', {'name': name, 'age': age}, where: 'id = ?', whereArgs: [id]);
  }

  Future<void> deleteUser(int id) async {
    final Database db = await database;
    await db.delete('users', where: 'id = ?', whereArgs: [id]);
  }
}

现在,在你的 Flutter 应用中使用这个 DatabaseHelper 类来进行数据库操作。例如,在 main.dart 中:

import 'package:flutter/material.dart';
import 'database_helper.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final DatabaseHelper dbHelper = DatabaseHelper();

  @override
  void initState() {
    super.initState();
    _insertData();
    _retrieveData();
  }

  Future<void> _insertData() async {
    await dbHelper.insertUser('Alice', 30);
    await dbHelper.insertUser('Bob', 25);
  }

  Future<void> _retrieveData() async {
    List<Map<String, dynamic>> users = await dbHelper.getUsers();
    print(users);
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Flutter Database Example'),
        ),
        body: Center(
          child: Text('Check the console for database output'),
        ),
      ),
    );
  }
}

在这个示例中,我们在 initState 方法中插入了两个用户,并检索了所有用户的数据,然后在控制台中打印出来。你可以根据需要在 UI 中显示这些数据,或者添加更多的数据库操作(如更新和删除用户)。

请注意,由于 sqflite_adapter 不是一个标准的 Flutter 插件,如果确实存在这样一个插件,你可能需要查阅其官方文档或源代码以获取具体的用法。上述示例是基于广泛使用的 sqflite 插件的。

回到顶部