[英]How to filter Future List in Flutter?
我需要過濾列表的幫助。
我在 initState 中填充列表:
Future _organisations;
Future<void> readJson() async {
final String response =
await rootBundle.loadString('assets/organisations.json');
final data = await json.decode(response);
List<Organization> temp = [];
for (var item in data) {
Organization place = Organization(
address: item['Address'],
contactInfo: item['Contact info'],
organization: item['Organization'],
phoneNumber: item['Phone number'],
shortDescription: item['Short description'],
subject: item['Subject'],
tags: item['Tags'],
);
temp.add(place);
}
temp.sort((a, b) => a.organization.compareTo(b.organization));
return temp;
}
@override
void initState() {
super.initState();
_organisations = readJson();
}
然后我在列表上方有一個按鈕,我想用它來過濾帶有 setState 的列表,但是它不起作用。 如何過濾未來類型的列表?
首先,您的方法readJson()
具有Future<void>
類型的返回值,這意味着您將永遠無法返回List<Organization>
。
此外,您正在使用異步操作,這意味着您將需要使用await
或then
在某些時候獲得您的價值。
以下是如何修復代碼的示例:
List<Organization> _organisations;
// Simply change the return type to Future<List<Organization>>
Future<List<Organization>> readJson() async {
final String response =
await rootBundle.loadString('assets/organisations.json');
final data = await json.decode(response);
List<Organization> temp = [];
for (var item in data) {
Organization place = Organization(
address: item['Address'],
contactInfo: item['Contact info'],
organization: item['Organization'],
phoneNumber: item['Phone number'],
shortDescription: item['Short description'],
subject: item['Subject'],
tags: item['Tags'],
);
temp.add(place);
}
/// Then you need to compare objects that are comparable.
/// For example if you want to sort your items by their address :
temp.sort((a, b) =>
a.address.toLowerCase().compareTo(b.address.toLowerCase())
);
return temp;
}
@override
void initState() {
super.initState();
/// As you cannot use await in initState you can use then
/// to perform an action once your asynchronous operation is
/// done.
///
/// In this case I am assigning the value to _organisations
/// and causing a rebuild of the interface with setState.
readJson().then((List<Organization> temp) {
setState(() => _organisations = temp);
});
}
Future<void>
不返回任何內容。 如果您希望它返回一個列表,它應該是Future<List>
。 當您對列表中的項目進行排序時,您將它們與什么進行比較? item[“組織”]屬於什么類型? 它必須是可比較的類型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.