这是我的地址按钮代码。我想在包含多个地址的地址数组中搜索一个地址。但是我找不到。这部分遇到了索引问题。如何调用索引循环?我什么办法都试过了。我现在能够在一个列表视图中显示所有地址。我想通过至少键入一个字母来搜索地址,以首先显示地址。
onSearchAddr(String text) {
if (text.isNotEmpty) {
setState(() {
for (var item in searchitems) {
// final addr = item.address!
// .where((element) => element.addr1!.contains(text))
// .toList();
// final itemList = searchitems
// .where((e) => e.address![0].addr1 == addr[0].addr1)
// .toList();
// print('addr: $addr');
// print('itemList: $itemList');
if (item.address![0].addr1.toString().contains(text)) {
searchitems.clear();
searchitems.add(item);
print('searchitems if: ${searchitems.length}');
print('searchitems if: ${searchitems[0].address!.length}');
} else {
print('Not Contain:');
}
}
});
} else {
setState(() {
searchitems.clear();
searchitems =
items.where((element) => element.custnum == searchText).toList();
print('searchitems else: ${searchitems.length}');
});
}
}
这是json
{
"items": [
{
"custnum": "",
"name": "",
"address": [
{
"shipto": 0,
"addr1": "",
"thanon": "",
"tambon": "",
"amphur": "",
"prov_code": "",
"province": "",
"zipcode": "",
"country": "",
"contact": "",
"postcode": ""
},
{
"shipto": 1,
"addr1": "",
"thanon": "",
"tambon": "",
"amphur": "",
"prov_code": "",
"province": "",
"zipcode": "",
"country": "",
"contact": "",
"postcode": ""
},
{
"shipto": 2,
"addr1": "",
"thanon": "",
"tambon": "",
"amphur": "",
"prov_code": "",
"province": "",
"zipcode": "",
"country": "",
"contact": "",
"postcode": ""
},
{
"shipto": 3,
"addr1": "",
"thanon": "",
"tambon": "",
"amphur": "",
"prov_code": "",
"province": "",
"zipcode": "",
"country": "",
"contact": "",
"postcode": ""
}
{
"custnum": "",
"name": "",
"address": [
{
"shipto": 0,
"addr1": "",
"thanon": "",
"tambon": "",
"amphur": "",
"prov_code": "",
"province": "",
"zipcode": "",
"country": "",
"contact": "",
"postcode": ""
},
{
"shipto": 1,
"addr1": "",
"thanon": "",
"tambon": "",
"amphur": "",
"prov_code": "",
"province": "",
"zipcode": "",
"country": "",
"contact": "",
"postcode": ""
},
]
}),
当你在list的循环中时,你不能清除list,所以将onSearchAddr
更改为:
onSearchAddr(String text) {
if (text.isNotEmpty) {
setState(() {
searchitems.clear();
for (var item in items) {
for (var address in item.address) {
if (address.addr1.toString().contains(text)) {
searchitems.add(item);
} else {
print('Not Contain:');
}
}
}
});
} else {
setState(() {
searchitems.clear();
searchitems =
items.where((element) => element.custnum == searchText).toList();
print('searchitems else: ${searchitems.length}');
});
}
}