使用 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

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

添加 pubspec.yamal 文件

资产:- 资产/hadith_db.db

最新更新