【发布时间】:2021-01-13 08:19:33
【问题描述】:
我正在尝试获取目录的内容并将其显示在屏幕上。
当我只有 1 个未来(并在方法中硬编码返回值)时,我能够显示它们。但是当我在未来中嵌入未来(我需要这样做以获取应用程序目录和文件列表)时,它就不起作用了。
这是我的代码:
Future<List<CardFileInfo>> _getFilelist() {
var localFileHelper = new LocalFileHelper();
return Future.value(localFileHelper.getFileList());
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Cards")
),
body: Center(
child: Column(
children: <Widget>[
FutureBuilder<List<CardFileInfo>>(
future: _getFilelist(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text("Files Found");
}
else {
return Text("Still looking");
}
} //end of builder
), //end of future builder
], //end of children
), //end of column
), //end of center
); //end of scaffold
}
这里是localFileHelper.getFileList()方法的代码:
List<CardFileInfo> getFileList() {
List<CardFileInfo> cardInfoList = [];
final dirName = getApplicationDocumentsDirectory();
// *** if I uncomment the following two lines, the process works ***
// cardInfoList.add(CardFileInfo("dummy.tsv"));
// return cardInfoList;
dirName.then((dir) { // <---------- problem seems occurs here with the future
final files = dir.list().toList();
files.then((values){
values.forEach((element) {
var type = element.path.toString().split(".").last.trim();
if (type == "tsv") {
var currCard = CardFileInfo(element.path.toString().trim());
cardInfoList.add(currCard);
}
}); //end of foreEach
return cardInfoList;
}); //end of files.then
}); //end of dirName.then
} //end of getFileList()
当我单步执行代码时,"return Text("Still looking");"行最多执行两次。
函数最终返回值,但看起来 FutureBuilder 没有等待足够长的时间来返回值。
我是 Flutter 和 Dart 的新手,这个问题真的让我很困惑。
【问题讨论】: