生成的布尔列表不能更改其值



我需要创建一个身份验证页面。它有位置。我已经从未来的api中收集了信息,并为它们分配了生成的bool列表,但我无法更改它们的值。以下是我的代码示例。。。

ListView.builder(
padding: EdgeInsets.fromLTRB(0,12,0,0),
shrinkWrap: true,
primary: false,
itemCount: snapshot.data!.locationList!.length,
itemBuilder: 
(context, index) {
final locations = snapshot.data!.locationList!;
List<bool>? x = List<bool>.generate(locations.length, (index) => false);
debugPrint(x[0].toString()); //false
debugPrint(locations[0].id.toString()); //1
return Padding(
padding: const EdgeInsets.fromLTRB(12,6,12,6),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text('${locations[index].name}', style: TextStyle(fontSize: 20),),
FlutterSwitch(
width: width*.2,
height: 50.0,
activeColor: col.mostDarkPurpleAccent,
toggleSize: width*.06,
value: LoginApi.distinctLocation.contains(index+1) ? !x[index] : x[index],
borderRadius: 30.0,
padding: 8.0,
onToggle: (bool val) {
debugPrint(val.toString()); //false
setState(() {
debugPrint('setState başı: '+x[index].toString()); //false
if (LoginApi.distinctLocation.contains(index+1)) {
debugPrint('if başı: '+x[index].toString()); //false
x[index] = !val;
debugPrint('if sonu: '+x[index].toString()); //true
} else {
debugPrint('else başı: '+x[index].toString()); //not in
x[index] = !val;
debugPrint('else sonu: '+x[index].toString()); //not in
}
debugPrint('setState sonu: '+x[index].toString()); //true
});
},
),
],
),
);
},
),

这里有代码,但我无法切换。出了什么问题?你能帮我吗?

如果在onToggle: (bool val){}中将值设置为x[index]并调用setState(),则您的值已经更改并影响视图。所以你不需要这样做:value:LoginApi.distinctLocation.contains(index+1) ? !x[index] : x[index],只使用:value: x[index],

最新更新