Flutter:如何使用path_provider将文件写入本地目录



我正在开发Flutter应用程序,需要将文件写入本地系统(iOS、Android以及Web(。我逻辑上遵循了关于读写文件的文档,并使用path_provider制作了一个测试功能的小示例:

import 'package:path_provider/path_provider.dart';
...
void _testPathProvider() async {
// Directory appDocDir = await getTemporaryDirectory(); // Using a different dir. not working either
// String appDocPath = appDocDir.path;
Directory appDocDir = await getApplicationDocumentsDirectory();
String appDocPath = appDocDir.path;
debugPrint('$appDocPath/my_file.txt');
// Save in local file system
var file = await File('$appDocPath/my_file.txt').writeAsString('hello!');
}

这个测试函数只是通过一个按钮调用的,没有什么疯狂的。但当我在浏览器&按下按钮,我得到以下错误:

Error: MissingPluginException(No implementation found for method getApplicationDocumentsDirectory on channel plugins.flutter.io/path_provider)
at Object.throw_ [as throw] (http://localhost:42561/dart_sdk.js:5067:11)
at MethodChannel._invokeMethod (http://localhost:42561/packages/flutter/src/services/restoration.dart.lib.js:1560:21)
at _invokeMethod.next (<anonymous>)
at http://localhost:42561/dart_sdk.js:40571:33
at _RootZone.runUnary (http://localhost:42561/dart_sdk.js:40441:59)
at _FutureListener.thenAwait.handleValue (http://localhost:42561/dart_sdk.js:35363:29)
at handleValueCallback (http://localhost:42561/dart_sdk.js:35931:49)
at Function._propagateToListeners (http://localhost:42561/dart_sdk.js:35969:17)
at _Future.new.[_completeWithValue] (http://localhost:42561/dart_sdk.js:35817:23)
at async._AsyncCallbackEntry.new.callback (http://localhost:42561/dart_sdk.js:35838:35)
at Object._microtaskLoop (http://localhost:42561/dart_sdk.js:40708:13)
at _startMicrotaskLoop (http://localhost:42561/dart_sdk.js:40714:13)
at http://localhost:42561/dart_sdk.js:36191:9

这个问题似乎是众所周知的,在这里和这里都遵循了建议,包括:

  • 运行flutter clean并重新获取包
  • 完全关闭应用程序并重新运行
  • 将Flutter升级到最新稳定版本
  • path_provider重新添加到我的pubspec.yaml

我使用的是最新版本的依赖项(path_provider: ^2.0.9(。

非常感谢您的帮助。

以下是注释中提到的数据uri方法的示例:

import 'dart:html' as html;
final bytes = utf8.encode('hello!');
final dataUri = 'data:text/plain;base64,${base64.encode(bytes)}';
html.document.createElement('a') as html.AnchorElement
..href = dataUri
..download = 'my_file.txt'
..dispatchEvent(html.Event.eventType('MouseEvent', 'click'));

请确保它位于仅在html可用时导入的dart文件中,或者最好使用package:universal_html

相关内容

  • 没有找到相关文章

最新更新