Flutter 异步函数完成后如何返回数据
假设我有以下文件夹结构:Flutter 异步函数完成后如何返回数据,flutter,asynchronous,dart,Flutter,Asynchronous,Dart,假设我有以下文件夹结构: People | |── John | |── img.png | |── info.json |── Craig | |── img.png | |── info.json |── Daniel | |── img.png | |── info.json 我想获得People文件夹中列出的每个文件夹的info.json。为此,我编写了一个函数: 导入'dart:convert'; 导入“dart:io”; 目录folderPath=目录(“
People
|
|── John
| |── img.png
| |── info.json
|── Craig
| |── img.png
| |── info.json
|── Daniel
| |── img.png
| |── info.json
我想获得People
文件夹中列出的每个文件夹的info.json
。为此,我编写了一个函数:
导入'dart:convert';
导入“dart:io”;
目录folderPath=目录(“/storage/people/”);
Future getData()异步{
列表数据=[];
folderPath.list().listen((e)async{//用于目录中的每个实体
var-path=e.path;
File infoFile=File(“$path/info.json”);
String infoString=await infoFile.readAsString();
Map info=jsonDecode(infoString);
数据。添加(项目);
});
返回数据;
}
不幸的是,它不起作用。函数不等待循环结束,并将数据
返回为空
循环完成后,函数是否有返回数据的方法?您应该尝试在folderPath.list()上使用本机for循环。
在Dart中,使用for循环将自动告诉函数在返回任何内容之前等待它结束。您应该尝试在folderPath.list()上使用本机for循环。
在Dart中,使用for循环将自动告诉函数在返回任何内容之前等待它结束。您能试试这个吗
Directory folderPath = Directory("/storage/people/");
Future<List> getData() async {
List data = [];
List<FileSystemEntity> entities = folderPath.listSync();
for (FileSystemEntity e in entities) {
var path = e.path;
File infoFile = File("$path/info.json");
String infoString = await infoFile.readAsString();
Map info = json.decode(infoString);
data.add(info);
}
return data;
}
Directory folderPath=Directory(“/storage/people/”);
Future getData()异步{
列表数据=[];
List entities=folderPath.listSync();
for(实体中的文件系统){
var-path=e.path;
File infoFile=File(“$path/info.json”);
String infoString=await infoFile.readAsString();
Map info=json.decode(infoString);
数据。添加(信息);
}
返回数据;
}
你能试试这个吗
Directory folderPath = Directory("/storage/people/");
Future<List> getData() async {
List data = [];
List<FileSystemEntity> entities = folderPath.listSync();
for (FileSystemEntity e in entities) {
var path = e.path;
File infoFile = File("$path/info.json");
String infoString = await infoFile.readAsString();
Map info = json.decode(infoString);
data.add(info);
}
return data;
}
Directory folderPath=Directory(“/storage/people/”);
Future getData()异步{
列表数据=[];
List entities=folderPath.listSync();
for(实体中的文件系统){
var-path=e.path;
File infoFile=File(“$path/info.json”);
String infoString=await infoFile.readAsString();
Map info=json.decode(infoString);
数据。添加(信息);
}
返回数据;
}