未处理的异常:FileSystemException:无法打开文件,路径='assets / xml / strings.xml'(操作系统错误:无此类文件或目录,errno = 2)

时间:2019-12-21 14:28:49

标签: flutter dart

我开始研究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)

在这里,如何在项目结构中设置我的资产: enter image description here

所以,在我看来,我对所有设置都正确,这是什么问题?

1 个答案:

答案 0 :(得分:1)

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

如果要在WidgetsFlutterBinding.ensureInitialized()函数之前使用rootBundle,还请先调用runApp

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);
}
相关问题