首页 > 解决方案 > 使用 rootBundle.load() 阻塞 UI 的大型数据库负载

问题描述

我在资产文件夹中有一个大型数据库(大约 130mb)。但是当我使用 rootBundle.load() 时,UI 会阻塞 3-4 秒。有什么解决办法吗?

代码:

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

    bool fileExists = File(path).existsSync();
    if (!fileExists) {
      // Should happen only the first time you launch your application
      print("Creating new copy from asset");

      // Copy from asset
      print("starting root bundle");
      ByteData data = await rootBundle.load(join("assets", "hadith_db.db"));
      print("starting buffer");
      List<int> bytes = data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
      print("finished buffer");
      await File(path).writeAsBytes(bytes);
    }

    // open the database
    Database db = await openDatabase(path, readOnly: true);

    return db;
  }

注意:为了显示这些数据,我正在使用 FutureBuilder

标签: dartflutter

解决方案


您可以使用飞镖隔离物。Dart 隔离用于并发编程,并创建类似于线程但不共享内存的工作人员,它们仅通过消息传递工作。有关更多信息,请参阅:https ://api.dartlang.org/stable/2.2.0/dart-isolate/dart-isolate-library.html


推荐阅读