【问题标题】:FileSystemException: Cannot open file, path = 'assets/busStops.txt' (OS Error: No such file or directory, errno = 2)FileSystemException:无法打开文件,路径 = 'assets/busStops.txt'(操作系统错误:没有这样的文件或目录,errno = 2)
【发布时间】:2021-01-27 12:59:15
【问题描述】:

我似乎无法加载存储在资产中的 txt 文件。每当我尝试访问它时,都会收到以下错误:

FileSystemException: Cannot open file, path = 'assets/busStops.txt' (OS Error: No such file or directory, errno = 2)

我也将该文件添加到了我的 pubspec 文件中:

  assets:
    - assets/BusSD.png
    - assets/SubtractBD.png
    - assets/VectorDD.png
    - assets/busRoutes.txt
    - assets/busStops.txt

这是我访问文件的代码


class FileUtilsBusStopInfo {
  static Future<String> get getFilePath async {
    final directory = await getApplicationDocumentsDirectory();
    return directory.path;
  }

  static Future<File> get getFile async {
    //final path = await getFilePath;

    return File('assets/busStops.txt');
  }

  static Future<File> saveToFile(String data) async {
    final file = await getFile;
    return file.writeAsString(data);
  }

  static Future<String> readFromFile() async {
    try {
      final file = await getFile;
      String fileContents = await file.readAsString();

      print(fileContents);
      return fileContents;
    } catch (e) {
      print(e);
      print('returning blank');
      return "";
    }
  }
}

图像加载正常。我可以做些什么来解决这个问题?提前谢谢!

【问题讨论】:

  • 你有没有先flutter pub get再运行代码?

标签: android flutter dart


【解决方案1】:

尝试通过以下方式加载文件:

import 'package:flutter/services.dart' show rootBundle;

// Method
final data = rootBundle.load('assets/busStops.txt');
// ...

Flutter 中的资产由其服务加载,而不是从设备的文件系统中加载。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-16
    • 2022-12-16
    • 2018-03-28
    • 2020-08-10
    • 2020-05-13
    • 2020-01-13
    • 2020-02-15
    • 2022-08-18
    相关资源
    最近更新 更多