gpt4 book ai didi

flutter - Flutter:如何通过ToggleButtons对ListView进行排序

转载 作者:行者123 更新时间:2023-12-03 04:47:00 27 4
gpt4 key购买 nike

我有一个列表 View ,如下所示:

enter image description here

列表 View 的代码:

_listCountry(index) {
Country country = _country[index];
return Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget> [
Text('${country.id}'),
Text(country.name),
Text('${country.population}'),
],
);
}

我创建了排序方法,效果很好:

_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));
});
}

那么,如何将这些方法放入OnpressedToggleButtons中,以便在按下时可以进行排序? 这是“切换按钮”代码:

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()中创建它:
@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();
}

当您选择 切换按钮,称这样的方法:
 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 - Flutter:如何通过ToggleButtons对ListView进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62107557/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com