Flutter数据库交互插件thikdb的使用

特性

Hive实现用于轻松创建简单的配置。

  • 快速实现配置(例如:应用程序配置)并将其数据保存到Hive数据库中。

开始使用

创建一个继承自ThikDb的类,并调用open()方法。例如:

class AppConfig extends ThikDb {
  static const String dbDir = "db"; // 在应用程序目录下创建名为'db'的目录
  static late final AppConfig _; // 静态实例以快速访问
  AppConfig() : super("app_config"); // 数据库表名

  static Future<void> init() async {
    _ = AppConfig(); // 初始化静态实例
    String dbFullPath = (await _.open(dbDirName: dbDir))!; // 打开数据库并获取路径
    dbPath = dbFullPath; // 设置数据库路径
  }
}

使用方法

在类中定义一些可以直接访问的静态变量。完整的示例可以在/example文件夹中找到。

示例代码

static String get testStringVar => _.get("testStringVar", ""); // 获取键值,默认为空字符串
static set testStringVar(String value) => _.put("testStringVar", value); // 设置键值

// 获取应用资源目录列表
call listAppDirectory() to get simple app folder for some goal, ex: for save big file

完整示例代码

以下是一个完整的示例,展示了如何使用thikdb插件进行数据库操作。

main.dart

import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:thikdb/thikdb.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  debugPrint(Directory.current.path);
  AppConfig.init().whenComplete(() {
    runApp(const MyApp());
  });
}

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

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'ThikDb demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const SafeArea(child: Material(child: AppWg())),
    );
  }
}

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

  [@override](/user/override)
  Widget build(BuildContext context) {
    AppCtl ctl = Get.put(AppCtl());

    return Column(
      children: [
        FutureBuilder(
          future: AppConfig._.listAppDirectory(),
          builder: (context, snapshot) {
            if (snapshot.connectionState != ConnectionState.done) {
              return Container();
            }
            List<DropdownMenuEntry<String>> dropDownList = snapshot.data!
                .map((e) => DropdownMenuEntry<String>(value: e, label: e))
                .toList();
            return DropdownMenu<String>(
              width: 500,
              initialSelection: AppConfig.testAppResVar,
              controller: TextEditingController(),
              label: const Text('testAppResVar'),
              dropdownMenuEntries: dropDownList,
              onSelected: (String? selectedResDir) {
                AppConfig.testAppResVar = selectedResDir ?? "";
              },
            );
          },
        ),
        Obx(() {
          List<DropdownMenuEntry<String>> dropDownList = ctl.testListAppDirVar.value
              .map((e) => DropdownMenuEntry<String>(value: e, label: e))
              .toList();
          return DropdownMenu<String>(
            width: 500,
            initialSelection: AppConfig.testAppResVar,
            label: const Text('testAppResVar'),
            dropdownMenuEntries: dropDownList,
            onSelected: (String? selectedResDir) {
              AppConfig.testAppResVar = selectedResDir ?? "";
            },
          );
        }),
        Text(AppConfig.dbPath),
        Obx(() => Text(ctl.testStringVar.value)),
        ElevatedButton(
          onPressed: () {
            AppConfig.testStringVar = AppConfig.testStringVar.isEmpty ? "not_empty" : "";
            ctl.testStringVar.value = AppConfig.testStringVar;
          },
          child: const Text("testStringVar"),
        ),
        Obx(() => Text(ctl.testDoubleVar.toString())),
        ElevatedButton(
          onPressed: () {
            AppConfig.testDoubleVar = AppConfig.testDoubleVar == 0.0 ? 1.2 : 0.0;
            ctl.testDoubleVar.value = AppConfig.testDoubleVar;
          },
          child: const Text("testDoubleVar"),
        ),
        Obx(() => Text(ctl.testListVar.toString())),
        ElevatedButton(
          onPressed: () {
            AppConfig.testListVar = AppConfig.testListVar.isEmpty ? <double>[0, 1, 2, 3] : <double>[];
            ctl.testListVar.value = AppConfig.testListVar;
          },
          child: const Text("testListVar"),
        ),
        Obx(() => Text(ctl.testMapVar.toString())),
        ElevatedButton(
          onPressed: () {
            AppConfig.testMapVar = AppConfig.testMapVar.isEmpty ? {"A": 1, "b": 3} : {};
            ctl.testMapVar.value = AppConfig.testMapVar;
          },
          child: const Text("testMapVar"),
        ),
        Obx(() => Text(ctl.testAlignVar.toString())),
        ElevatedButton(
          onPressed: () {
            AppConfig.testAlignVar = AppConfig.testAlignVar == Alignment.center
                ? Alignment.bottomLeft
                : Alignment.center;
            ctl.testAlignVar.value = AppConfig.testAlignVar;
          },
          child: const Text("testAlignVar"),
        ),
        Obx(() => Text(ctl.testNullableVar.toString())),
        ElevatedButton(
          onPressed: () {
            AppConfig.testNullableVar = AppConfig.testNullableVar == null ? "not_null" : null;
            ctl.testNullableVar.value = AppConfig.testNullableVar;
          },
          child: const Text("testNullableVar"),
        ),
        ElevatedButton(
          onPressed: () {
            AppConfig._.close().whenComplete(() {
              SystemNavigator.pop();
            });
          },
          child: const Text("Close and exit"),
        ),
      ],
    );
  }
}

class AppCtl extends GetxController {
  Rx<List<String>> testListAppDirVar = Rx<List<String>>(AppConfig.listAppDir);
  RxString testAppResVar = RxString(AppConfig.testAppResVar);
  RxString testStringVar = RxString(AppConfig.testStringVar);
  RxDouble testDoubleVar = RxDouble(AppConfig.testDoubleVar);
  RxList<double> testListVar = RxList<double>(AppConfig.testListVar);
  RxMap testMapVar = RxMap(AppConfig.testMapVar);
  Rx<Alignment> testAlignVar = Rx<Alignment>(AppConfig.testAlignVar);
  RxnString testNullableVar = RxnString(AppConfig.testNullableVar);
}

class AppConfig extends ThikDb {
  static const String dbDir = "db";
  static late final AppConfig _;
  AppConfig() : super("app_config");

  static Future<void> init() async {
    _ = AppConfig();
    String dbFullPath = (await _.open(initDirName: dbDir))!;
    dbPath = dbFullPath;
    listAppDir = await _.listAppDirectory();
  }

  static List<String> get listAppDir => _.get("listAppDir", <String>[]);
  static set listAppDir(List<String> value) => _.put("listAppDir", value);

  static String get testAppResVar => _.get("testAppResVar", "");
  static set testAppResVar(String value) => _.put("testAppResVar", value);

  static String get testStringVar => _.get("testStringVar", "");
  static set testStringVar(String value) => _.put("testStringVar", value);

  static double get testDoubleVar => _.get("testDoubleVar", 0.0);
  static set testDoubleVar(double value) => _.put("testDoubleVar", value);

  static List<double> get testListVar => _.get("testListVar", <double>[]);
  static set testListVar(List<double> value) => _.put("testListVar", value);

  static Map get testMapVar => _.get("testMapVar", {});
  static set testMapVar(Map value) => _.put("testMapVar", value);

  static Alignment get testAlignVar => _.get("testAlignVar", Alignment.center);
  static set testAlignVar(Alignment value) => _.put("testAlignVar", value);

  static String get dbPath => _.get("dbPath", "");
  static set dbPath(String value) => _.put("dbPath", value);

  static String? get testNullableVar => _.box.get("testNullableVar");
  static set testNullableVar(String? value) =>
      null == value ? _.box.delete("testNullableVar") : _.box.put("testNullableVar", value);
}

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

1 回复

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


thinkdb 是一个用于在 Flutter 应用中与数据库进行交互的插件。它主要用于简化数据库操作,提供了一种更直观的方式来执行 CRUD(创建、读取、更新、删除)操作。以下是如何使用 thinkdb 插件的基本步骤和示例。

1. 安装 thinkdb 插件

首先,你需要在 pubspec.yaml 文件中添加 thinkdb 依赖:

dependencies:
  flutter:
    sdk: flutter
  thinkdb: ^0.0.1  # 请根据实际版本号进行替换

然后运行 flutter pub get 来安装依赖。

2. 初始化数据库

在使用 thinkdb 之前,你需要初始化数据库连接。通常,你会在应用的 main 函数中进行初始化。

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

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  
  // 初始化数据库
  await ThinkDB.init(
    host: 'localhost',
    port: 3306,
    user: 'root',
    password: 'password',
    database: 'mydatabase',
  );

  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'ThinkDB Example',
      home: HomeScreen(),
    );
  }
}

3. 执行数据库操作

thinkdb 提供了简单的方法来执行数据库操作。以下是一些常见的操作示例。

查询数据

class HomeScreen extends StatelessWidget {
  Future<List<Map<String, dynamic>>> fetchData() async {
    return await ThinkDB.query('SELECT * FROM users');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('ThinkDB Example'),
      ),
      body: FutureBuilder<List<Map<String, dynamic>>>(
        future: fetchData(),
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting) {
            return Center(child: CircularProgressIndicator());
          } else if (snapshot.hasError) {
            return Center(child: 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']),
                  subtitle: Text(user['email']),
                );
              },
            );
          }
        },
      ),
    );
  }
}

插入数据

Future<void> insertUser(String name, String email) async {
  await ThinkDB.execute(
    'INSERT INTO users (name, email) VALUES (?, ?)',
    [name, email],
  );
}

更新数据

Future<void> updateUser(int id, String name, String email) async {
  await ThinkDB.execute(
    'UPDATE users SET name = ?, email = ? WHERE id = ?',
    [name, email, id],
  );
}

删除数据

Future<void> deleteUser(int id) async {
  await ThinkDB.execute(
    'DELETE FROM users WHERE id = ?',
    [id],
  );
}

4. 关闭数据库连接

在应用退出时,你应该关闭数据库连接以释放资源。

void dispose() async {
  await ThinkDB.close();
}

5. 错误处理

在执行数据库操作时,可能会遇到错误。你可以使用 try-catch 来捕获并处理这些错误。

Future<void> safeInsertUser(String name, String email) async {
  try {
    await ThinkDB.execute(
      'INSERT INTO users (name, email) VALUES (?, ?)',
      [name, email],
    );
  } catch (e) {
    print('Error inserting user: $e');
  }
}
回到顶部