Flutter:如何通过ToggleButtons对ListView进行排序 [英] Flutter: How to sort ListView by ToggleButtons
本文介绍了Flutter:如何通过ToggleButtons对ListView进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的列表视图如下:
列表视图的代码:
_listCountry(index) {
Country country = _country[index];
return Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget> [
Text('${country.id}'),
Text(country.name),
Text('${country.population}'),
],
);
}
我创建了排序方法,效果很好:
And I created methods to sort, it worked fine:
_onSortID() {
setState(() {
_country.sort((a, b) => b.id.compareTo(a.id));
});
}
_onSortName() {
setState(() {
_country.sort((a, b) => b.name.compareTo(a.name));
});
}
_onSortPopulation() {
setState(() {
_country.sort((b, a) => b.population.compareTo(a.population));
});
}
所以我如何将这些方法纳入
,以便它们在按下时可以排序?这是切换按钮代码: ToggleButtons
的按下
So how do I get these methods into the Onpressed
of ToggleButtons
so that they can sort when pressed? This is the Toggle Button code:
ToggleButtons(
children: <Widget> [
Text('Country ID'),
Text('Country Name'),
Text('Country Population')
],
onPressed: (int index) {
setState(() {
for (int buttonIndex = 0; buttonIndex < isSelected.length; buttonIndex++) {
if (buttonIndex == index) {
isSelected[buttonIndex] = !isSelected[buttonIndex];
} else {
isSelected[buttonIndex] = false;
}
}
});
},
isSelected: isSelected,
)
推荐答案
尝试一下:
定义方法列表
List sortMethods;
然后在 initState()中创建它,如下所示:
Then create it in initState() like this :
@override
initState() {
sortMethods = List.of({
() => setState(
() {
_country.sort((a, b) => b.id.compareTo(a.id));
},
),
() => setState(() {
_country.sort((a, b) => b.name.compareTo(a.name));
}),
() => setState(() {
_country.sort((a, b) => b.population.compareTo(a.population));
})
});
super.initState();
}
当您选择 ToggleButton 时,调用类似
onPressed: (int index) {
for (int buttonIndex = 0; buttonIndex < isSelected.length; buttonIndex++) {
if (buttonIndex == index) {
isSelected[buttonIndex] = !isSelected[buttonIndex];
} else {
isSelected[buttonIndex] = false;
}
sortMethods[index]();
}
}
这篇关于Flutter:如何通过ToggleButtons对ListView进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文