錯誤應該很清楚,但我不確定如何解決它。
基本上,我有一個流構建器,我每秒通過 getData() 方法呼叫一次,用新資料更新我的 SfCalendar。
Stream<DataSource> getData() async* {
await Future.delayed(const Duration(seconds: 1)); //Mock delay
List<Appointment> appointments = foo() as List<Appointment>;
List<CalendarResource> resources = bar() as List<CalendarResource>;
DataSource data = DataSource(appointments, resources);
print("Fetched Data");
yield data;
}
但是我的約會方法 foo() 的型別是 Future<List> 而不是 List。
Future<List<Appointment>> foo() async {
var url0 = Uri.https(
"uri",
"/profiles.json");
List<Appointment> appointments = [];
try {
final response = await dio.get(url0.toString());
//final Random random = Random();
//_colorCollection[random.nextInt(9)];
response.data.forEach((key, value) {
appointments.add(
Appointment(
id: int.parse(
value["id"],
),
startTime: DateTime.parse(value["startTime"]),
endTime: DateTime.parse(value["endTime"]),
),
);
});
} catch (error) {
print(error);
}
return appointments;
}
這就是錯誤應該告訴的,是嗎?我嘗試從 foo() 約會中洗掉 Future 演員表,但后來我無法使用異步。我也嘗試回傳 Future.value(appointments) 但同樣的錯誤。
這是我在 initState() 中呼叫我的 Stream 的地方:
@override
void initState() {
super.initState();
print("Creating a sample stream...");
Stream<DataSource> stream = getData();
print("Created the stream");
stream.listen((data) {
print("DataReceived");
}, onDone: () {
print("Task Done");
}, one rror: (error) {
print(error);
});
print("code controller is here");
}
謝謝,請在可能的情況下提供幫助
uj5u.com熱心網友回復:
就像 JavaScript 一樣,異步函式總是回傳一個 Future。這就是為什么從回傳型別中洗掉 Future 時不能使用 async 的原因。
由于您不是在等待 Future 解決,因此您實際上是在嘗試將 Future 轉換為 List,這不是有效的轉換。您需要做的就是等待函式完成,以便它決議為一個串列:
List<Appointment> appointments = await foo() as List<Appointment>;
而且,由于您的回傳型別是 Future<List<Appointment>>,您實際上并不需要轉換結果。
List<Appointment> appointments = await foo();
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/331000.html
