单选列表
需求:只选数组中的某一值,但选择了一个值时其他的不会被选择
方法:将数组遍历出来,再额外声明一个变量a;然后将遍历出来的index赋值给变量a;此时只需判断index是否等于a;当index==a时,该值被选择
声明一个数组并将其遍历出来
int selectIndex =0;
List model = [1,2,3,4,5];
Column(
children: model.map((index){
return InkWell(
onTap:(){
setState((){selectIndex =index;},
)
}
);
}).toList;
),
//代码的关键比较 当selectIndex和index一致的时候则选中
if(selectIndex==index){
print("选择了该值");
}
多选列表
int roomExistPeople = 10;
bool isSelect = false;
List<bool> isSelectedList = [];
ListView(
children: List.generate(
roomExistPeople,
(index) {
return CheckboxListTile(
title: Text(
'name。。。。。',
style: TextStyle(
fontSize: 10.sp,
color: Colors.black,
),
),
value: isSelectedList.isEmpty
? false
: isSelectedList[index],
onChanged: (bool value) {
setState(() {
if (isSelectedList.isEmpty) {
isSelectedList = List.generate(
roomExistPeople, (index) => false);
}
isSelectedList[index] = value;
print(
isSelectedList
.asMap()
.entries
.where((element) => element.value == true)
.map((e) => e.key)
.join(','),
);
});
},
);
},
),
),