【问题标题】:Unable to read a file in local directory with Flutter无法使用 Flutter 读取本地目录中的文件
【发布时间】:2022-09-27 15:37:18
【问题描述】:

我正在创建一个将文件写入本地目录并需要稍后访问它的应用程序。一个问题:当我尝试读取文件时,该过程永远不会结束(并且不会引发错误)。

这是我从代码中提取的方法。

import \'dart:convert\';
import \'dart:io\';
import \"package:path_provider/path_provider.dart\";

Future<Map<String, dynamic>> getFile(String path) async {
  final dir = await getApplicationDocumentsDirectory();
  final rootPath = dir.path;
  final file = File(\"$rootPath/$path\");
  print(\"getting file at : \'$rootPath/$path\'\");
  print(\"reading data...\");
  final content = file.readAsStringSync(); // what is happening here??
  print(\"file read!\"); // this line is never reached.
  print(\"The content has been decoded as a string : \'$content\'\");
  return content;
}

当我执行此代码时,在控制台中“读取数据...”后什么也没有发生:

I/flutter (16575): getting file at : \'/data/user/0/com.example.app/app_flutter/Folder/subfolder/file.json\'
I/flutter (16575): reading data...
D/EGL_emulation(16575): app_time_stats: avg=6.00ms min=3.32ms max=39.17ms count=60
D/EGL_emulation(16575): app_time_stats: avg=4.48ms min=2.67ms max=6.84ms count=57
etc.
... this line above is repeating itself indefinitely and my app is showing the loader

注意:写入文件的功能工作得很好。

注意:我在 File 的异步方法 readAsString() 上遇到了同样的问题。

我只想读取本地存储的 JSON 文件...

  • 你的潜在文件是否存在?
  • 它确实不存在。问题就是由此而来。我在此评论下的答案中解释了它。

标签: flutter file dart


【解决方案1】:

我解决了这个问题。

问题是我的文件不存在,创建文件时路径出错(所以当我创建文件时,文件的路径不同,当我试图用另一种方法访问它时)。

无论如何,我认为代码的反应是这样的,这很奇怪。它应该打印一些东西,或者告诉我出了什么问题,至少。我不得不考虑解决方法以查看问题所在...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-05
    • 1970-01-01
    • 2021-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-06
    相关资源
    最近更新 更多