【问题标题】:Is there any example of pre-populated database usage in Flutter?Flutter 中是否有任何预填充数据库使用的示例?
【发布时间】:2019-10-21 17:34:40
【问题描述】:

Flutter 中是否有任何预填充数据库使用的示例? 我不需要 CRUD 示例。此时我只需要从数据库中读取数据。 我是 Flutter 的新手,所以一步一步的教程会很好。

【问题讨论】:

  • 哪种数据库? sqlite? firestore 火力基地?
  • 您可以只在共享首选项中存储一个布尔值,以检查您是否已经在数据库中保存了数据,如果为 false 则保存并将该布尔值更改为 true,以便它不会再次运行
  • @BrunoSponsorship 我需要离线使用我的应用程序,所以 sqlite 是很好的变体。我也认为 hive 可能是一个很好的变体,但我不知道它是否接受 JOINS。

标签: database sqlite flutter sqflite


【解决方案1】:

您可以将您的应用与assets 文件夹中预先填充的sqlite 数据库捆绑在一起。然后在第一次运行时将数据库从资产复制到应用程序的工作目录。以下代码示例显示了一种方法(打印语句只是为了显示发生了什么):

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

Future<Database> initDatabase() async {
    var databasesPath = await getDatabasesPath();
    var path = join(databasesPath, "app.v1.db");

    // Check if the database exists
    var exists = await databaseExists(path);

    if (!exists) {
      // Should happen only the first time you launch your application
      print("Creating new copy from asset");

      // Make sure the parent directory exists
      try {
        await Directory(dirname(path)).create(recursive: true);
      } catch (e) {
        print(e.toString());
      }

      // Copy from asset
      ByteData data = await rootBundle.load(join("assets", "prepopulated.db"));
      List<int> bytes =
          data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);

      // Write and flush the bytes written
      await File(path).writeAsBytes(bytes, flush: true);
      print("Database created successfully");
    } else {
      print("Opening existing database");
    }

    // open the database
    return await openDatabase(path, version: "1", readOnly: false);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-02
    • 1970-01-01
    • 2018-06-22
    • 2012-01-10
    • 1970-01-01
    • 2012-10-07
    相关资源
    最近更新 更多