我开始研究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)
所以,在我看来,我对所有设置都正确,这是什么问题?
答案 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);
}