如何将 getApplicationDocumentsDirectory() 与 flutter for web 结合使用

ima*_*ane 9 flutter

我是 flutter 的初学者,我想在我的 Flutter 应用程序中使用 sqflite 包来使用 SQlite 数据库,我在 chrome 上运行我的 flutter 应用程序,因为我的模拟器无法工作,我在代码中使用,getApplicationDocumentsDirectory但出现错误:

Error: MissingPluginException(No implementation found for method getApplicationDocumentsDirectory on channel plugins.flutter.io/path_provider)

我在一篇文章中读到:在开始向应用程序添加网络支持后,我遇到了这个问题。getApplicationDocumentsDirectory 函数仅支持 iOS 和 Android (docs)。我添加了对网络的检查,并更改了设置目录的方式,为我修复了“未找到方法的实现”。

要判断平台是否是 Web,请使用 Flutter 的 kIsWeb:

Then handle setting the directory accordingly:

if (kIsWeb) {
    // Set web-specific directory
} else {
    appDocumentDirectory = await path_provider.getApplicationDocumentsDirectory();
}
Run Code Online (Sandbox Code Playgroud)

但我不知道如何设置特定于网络的目录。

我的代码是

    if (_database != null) {
      return _database;
    }
    _database = await _initializeDatabase();
    return _database;
  }

  Future<Database> _initializeDatabase() async {
    Directory directory = await getApplicationDocumentsDirectory();
    String path = join(directory.path, 'annonce_database.db');
    return await openDatabase(path, version: _dbVersion, onCreate: _onCreate);
  }```
Run Code Online (Sandbox Code Playgroud)

fsa*_*sch 6

getApplicationDocumentsDirectory() 不适用于 Web,因此使用您的代码,您必须修改 _initializeDatabase() 函数,并替换为字符串路径路由,以便在 Web 中使用它(即项目内的资产文件夹)忘记导入 KIsWeb

import 'package:flutter/foundation.dart' show kIsWeb;
...
Future<Database> _initializeDatabase() async {
//here
    if (kIsWeb) {
        String path = "/assets/db";
    } else {
        Directory directory = await getApplicationDocumentsDirectory();
        String path = join(directory.path, 'annonce_database.db');
    }
    return await openDatabase(path, version: _dbVersion, onCreate: _onCreate);
}
Run Code Online (Sandbox Code Playgroud)