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

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

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

示例代码

import 'package:example/database/parameters.dart';
import 'package:example/database/entity/model.dart';
import 'package:flutter/material.dart';
import 'package:sqflite_simple_dao_backend/database/database/dao_connector.dart';
import 'package:sqflite_simple_dao_backend/database/database/sql_builder.dart';
import 'package:sqflite_simple_dao_backend/database/utilities/print_handle.dart';
import 'main.reflectable.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  Parameters();
  initializeReflectable();
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

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

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() async {
    Dao dao = const Dao();

    List<Model> models = [
      Model.all(nr: 1, date: '2020-12-01', name: 'test1', price: 15.25),
      Model.all(nr: 2, date: '2020-12-02', name: 'test2', price: 15.25),
      Model.all(nr: 3, date: '2020-12-03', name: 'test3', price: 15.25),
      Model.all(nr: 4, date: '2020-12-04', name: 'test4', price: 15.25),
      Model.all(nr: 5, date: '2020-12-05', name: 'test5', price: 15.25),
      Model.all(nr: 6, date: '2020-12-06', name: 'test6', price: 15.25),
      Model.all(nr: 7, date: '2020-12-07', name: 'test7', price: 15.25),
    ];
    await models[0].insert();

    await dao.batchInsert(objectsToInsert: models);

    PrintHandle.warningLogger.t('Printing data before update and delete');
    await printData(d(dao);
    for (var x in models) {
      x.price = 20.25;
    }
    await models[0].update();

    await dao.batchUpdate(objectsToUpdate: models);

    PrintHandle.warningLogger
        .t('Printing data after update and before before delete');

    await printData(d dao;

    PrintHandle.warningLogger.t('Printing full model');
    var modelsResult = await dao.select&lt;Model&gt;(
        sqlBuilder: SqlBuilder().querySelect().queryFrom(table: 'models'),
        model: Model(),
        print: true);

    for (var x in modelsResult) {
      PrintHandle.warningLogger.i(x.toJson());
    }

    await models[0].delete();

    await dao.batchDelete(objectsToDelete: models.sublist(1, 3));

    setState(() {
      // This call to setState tells the Flutter framework that something has changed in this State, which causes it rerun the build method below so that the display can reflect the updated values. If we changed _counter without calling setState(), then the build method would not be called again, and so nothing would appear to happen.
      _counter++;
    });
  }

  Future&lt;void&gt; printData(Dao dao) async {
    var response = await dao.select(
        sqlBuilder: SqlBuilder()
            .querySelect(fields: [
              'nr',
              'date',
              'name',
              'price',
            ])
            .queryFrom(table: 'models')
            .queryOrder());
    for (var element in response) {
      PrintHandle.warningLogger.i(
          'nr: ${element['nr']} -- date: ${element['date']} -- name: ${element['name']} -- price: ${element['price']}");
    }
  }

  @override
  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance as done by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods fast, so that you can just rebuild anything that needs updating rather than having to individually change instances of widgets.
    //
    // Column has various properties to control how it sizes itself and how it positions its children. Here we use mainAxisAlignment to center the children vertically; the main axis here is the vertical axis because Columns are vertical (the cross axis would be horizontal).
    //
    // TRY THIS: Invoke "debug painting" (choose the "Toggle Debug Paint" action in the IDE, or press "p" in the console), to see the wireframe for each widget.
    return Scaffold(
      appBar: AppBar(
        // TRY THIS: Try changing the color here to a specific color (to Colors.amber, perhaps?) and trigger a hot reload to see the AppBar change color while the other colors stay the same.
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        // Here we take the value from the MyHomePage object that was created by the App.build method, and use it to set our appBar title.
        title: Text(widget.title),
      ),
      body: Center(
        // Center is a layout widget. It single child and positions it in the middle of the parent.
        child: Column(
          // Column is also a layout widget. It list of children and arranges them vertically. By default, it sizes itself to fit its children horizontally, and tries to be as tall as its parent.
          // Column has various properties to control how it sizes itself and how it positions its children. Here we use mainAxisAlignment to center the children vertically; the main axis here is the vertical axis because Columns are vertical (the cross axis would be horizontal).
          // TRY THIS: Invoke "debug painting" (choose the "Toggle Debug Paint" action in the IDE, or press "p" in the console), to see the wireframe for each widget.
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headlineMedium,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods methods.
    );
  }
}

使用说明

1 Batch Insert:

var objectsToInsert = [object1, object2, object3];
int result = await daoConnector.batchInsert(objectsToInsert: objectsToInsert);
print('Number of rows inserted: $result');
  • Batch Update:
var objects = [object1, object2, object3];
int result = await daoConnector.batchInsertOrUpdate(objects: objects);
print('Number of rows affected: $result');
  • Batch Delete:
var objectsToDelete = [object1, object2, object3];
int result = await daoConnector.batchDelete(objectsToDelete: objectsToDelete);
print('Number of rows deleted: $result');
  • Batch Insert or Update:
var objects = [object1, object2, object3];
int result = await daoConnector.batchInsertOrUpdate(objects: objects);
print('Number of rows affected: $result');
  • Batch Insert or Delete:
var objects = [object1, object2, object3];
int result = await daoConnector.batchInsertOrDelete(objects: objects);
print('Number of rows affected: $result');
  • 注意事项:
    • 确保在修改 reflectable 包时执行以下命令以重新生成代码:
dart lib/builder.dart lib/main.dart

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

1 回复

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


当然,下面是一个关于如何使用 sqflite_simple_dao_backend 插件在 Flutter 中进行数据库操作的示例。这个插件通常用于简化数据库访问层的操作,特别是与 DAO(数据访问对象)模式结合使用时。

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

dependencies:
  flutter:
    sdk: flutter
  sqflite_simple_dao_backend: ^x.y.z  # 替换为最新版本号

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

示例代码

1. 定义数据模型

首先,定义一个数据模型,例如一个 User 类:

import 'package:sqflite_common/sqlite_api.dart';

class User {
  int? id;
  String name;
  int age;

  User({this.id, required this.name, required this.age});

  // 将对象映射到 Map
  Map<String, dynamic> toMap() {
    var map = <String, dynamic>{
      'name': name,
      'age': age,
    };
    if (id != null) {
      map['id'] = id;
    }
    return map;
  }

  // 从 Map 创建对象
  User.fromMap(Map<String, dynamic> map)
      : id = map['id'] as int?,
        name = map['name'] as String,
        age = map['age'] as int;
}

2. 定义 DAO 接口

接下来,定义一个 DAO 接口,用于数据库操作:

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

// 定义 UserDao 接口
abstract class UserDao implements BaseDao<User, int> {
  // 自定义查询方法
  Future<List<User>> findAll();
}

3. 实现 DAO

然后,实现 DAO 接口:

import 'package:sqflite_simple_dao_backend/sqflite_simple_dao_backend.dart';
import 'package:path_provider/path_provider.dart';
import 'dart:async';
import 'user.dart';

class UserDaoImpl extends BaseDaoImpl<User, int> implements UserDao {
  UserDaoImpl(Database db) : super(db, 'users', ['id'], User.fromMap, User.toMap);

  @override
  Future<List<User>> findAll() async {
    var result = await db.query('users', columns: null);
    List<User> users = result.map((row) => User.fromMap(row)).toList();
    return users;
  }
}

4. 使用 DAO 进行数据库操作

最后,在你的 Flutter 应用中使用 DAO 进行数据库操作:

import 'package:flutter/material.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path_provider/path_provider.dart';
import 'user_dao.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  late UserDao userDao;

  @override
  void initState() {
    super.initState();
    initDatabase();
  }

  Future<void> initDatabase() async {
    // 获取数据库路径
    var dbPath = await getDatabasesPath();
    String path = join(dbPath, 'test.db');

    // 打开数据库
    var db = await openDatabase(path, version: 1, onCreate: (Database db, int version) async {
      await db.execute('CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)');
    });

    // 初始化 DAO
    userDao = UserDaoImpl(db);

    // 插入一些数据
    await userDao.insert(User(name: 'Alice', age: 30));
    await userDao.insert(User(name: 'Bob', age: 25));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Database Example'),
      ),
      body: FutureBuilder<List<User>>(
        future: userDao.findAll(),
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            if (snapshot.hasError) {
              return Text('Error: ${snapshot.error}');
            } else {
              var users = snapshot.data ?? [];
              return ListView.builder(
                itemCount: users.length,
                itemBuilder: (context, index) {
                  var user = users[index];
                  return ListTile(
                    title: Text('${user.name}, Age: ${user.age}'),
                  );
                },
              );
            }
          } else {
            return Center(child: CircularProgressIndicator());
          }
        },
      ),
    );
  }
}

在这个示例中,我们:

  1. 定义了一个 User 数据模型。
  2. 创建了一个 UserDao 接口及其实现 UserDaoImpl
  3. 在 Flutter 应用中使用 UserDaoImpl 进行数据库操作,包括插入和查询数据。

这个示例展示了如何使用 sqflite_simple_dao_backend 插件来简化数据库操作。你可以根据需要进行扩展和修改。

回到顶部