gpt4 book ai didi

flutter - ListView Flutter 的单选

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

我正在尝试实现 listView在我的应用程序中进行单一选择,这样一旦点击列表中的项目,按下的项目颜色状态就会与其他项目不同。我已经做了我所知道的一切,但效果不佳。问题是,即使我的实现在按下时更新每个项目的状态,它也不会将其他项目重置为初始状态。
expected output

class BoxSelection{
bool isSelected;
String title;
String options;
BoxSelection({this.title, this.isSelected, this.options});
}


class _AddProjectState extends State<AddProject> {
List<BoxSelection> projectType = new List();
@override
void didChangeDependencies() {
super.didChangeDependencies();
projectType
.add(BoxSelection(title: "Building", isSelected: false, options: "A"));
projectType
.add(BoxSelection(title: "Gym House", isSelected: false, options: "B"));
projectType
.add(BoxSelection(title: "School", isSelected: false, options: "C"));
}

child: ListView.builder(
itemCount: projectType.length,
itemBuilder: (BuildContext context, int index) {
return GestureDetector(
onTap: () {
setState(() {
//here am trying to implement single selection for the options in the list but it don't work well
for(int i = 0; i < projectType.length; i++) {
if (i == index) {
setState(() {
projectType[index].isSelected = true;
});
} else {
setState(() {
projectType[index].isSelected = false;
});
}
}
});
},
child: BoxSelectionButton(
isSelected: projectType[index].isSelected,
option: projectType[index].options,
title: projectType[index].title,
),
);
},
),

最佳答案

您的问题是您正在使用 index访问 projectType元素,但您应该使用 i

if (i == index) {
setState(() {
projectType[i].isSelected = true;
});
} else {
setState(() {
projectType[i].isSelected = false;
});
}
无论如何,我认为您的代码可以改进,因为它的效率不如预期。您正在遍历整个列表并调用 setState在每次迭代中两次,在一次拍摄中就可以不必要地重新创建小部件树很多次。
  • 将当前选择保存在类级别变量中
    BoxSelection _selectedBox
  • 简化您的代码以直接对当前选择进行操作,而不是遍历整个列表
     onTap: () =>
    setState(() {
    if (_selectedBox != null) {
    _selectedBox.isSelected = false;
    }
    projectType[index].isSelected = !projectType[index].isSelected;
    _selectedBox = projectType[index];
    });
  • 关于flutter - ListView Flutter 的单选,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62499593/

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