【问题标题】:Unhandled Exception: FileSystemException: Cannot open file, path = 'assets/xml/strings.xml' (OS Error: No such file or directory, errno = 2)未处理的异常:FileSystemException:无法打开文件,路径 = 'assets/xml/strings.xml'(操作系统错误:没有这样的文件或目录,errno = 2)
【发布时间】:2019-12-21 14:28:49
【问题描述】:

我开始学习 Flutter,一切正常,但它不读取 xml 文件 这是 pubspec.yaml 部分:

flutter:
  uses-material-design: true
  assets:
    - assets/
    - assets/xml/strings.xml

这是应该读取 xml 的部分:

  void main(){
    String file = "";
    switch (type){
      case TYPE_STRING:
        file = 'assets/xml/strings.xml';
        break;
    }
    readFileAsync(file);
  }

  void readFileAsync(String filePath) {
    File file = new File(filePath);
    Future<String> futureContent = file.readAsString();
    futureContent.then((xmlString) => {
      parseXml(xmlString)
    });
  }

我得到的错误是

Unhandled Exception: FileSystemException: Cannot open file, path = 'assets/xml/strings.xml' (OS Error: No such file or directory, errno = 2)

我的资产在项目结构中的设置方式如下:

所以,在我看来,我设置的一切都正确,有什么问题?

【问题讨论】:

  • 相对路径要求当前工作目录按照您的预期设置。除非您明确要求 .it,否则很少会出现这种情况。尝试打印出 file.getAbsolutePath() 并查看 Java 当前的位置。
  • 使用rootBundle - 这就是你应该如何访问你的assets 文件夹 - 文档说:“加载此应用程序的AssetBundle。rootBundle包含打包的资源在构建应用程序时与应用程序一起使用。要将资源添加到应用程序的 rootBundle,请将它们添加到应用程序的 pubspec.yaml 清单的颤振部分的 assets 子部分。"

标签: flutter dart


【解决方案1】:

使用rootBundle 访问应用程序包中的资源。

如果你想在runApp函数之前使用rootBundle,也可以先调用WidgetsFlutterBinding.ensureInitialized()

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  String file = "";
  switch (type) {
    case TYPE_STRING:
      file = 'assets/xml/strings.xml';
      break;
  }
  readFileAsync(file);
}

Future<dynamic> readFileAsync(String filePath) async {
  String xmlString =  await rootBundle.loadString(filePath);
  print(xmlString);
  return parseXml(xmlString);
}

【讨论】:

  • 你救了我的命
  • 不理想,因为 rootBundle.loadstring 是异步的并且不返回字符串
猜你喜欢
  • 2022-12-16
  • 1970-01-01
  • 2020-02-15
  • 2019-06-29
  • 2022-01-16
  • 2018-03-28
  • 2020-08-10
  • 2020-05-13
  • 1970-01-01
相关资源
最近更新 更多