[英]Flutter : Boolean value in Checkbox doesn't change
我想建立一个复选框列表,当我按下添加按钮时该列表会增加。 但是复选框不起作用,所以我在复选框和复选框的值中打印 onChanged 的布尔值,我发现两者都是相同的,除了第一次按下(复选框仍然不起作用)。 我将复选框的值更改为“true”,但结果相同。 请帮助我制作正确的代码。我已经复制了我的所有代码,请检查 addList 函数。
import 'package:flutter/material.dart';
void main() => runApp(FirstPage());
class FirstPage extends StatefulWidget {
@override
_FirstPageState createState() => _FirstPageState();
}
class _FirstPageState extends State<FirstPage> {
List<bool> listBool = [];
List<Widget> listWidget = [];
void addList(Text text) {
int listLength = listWidget.length;
listBool.add(false);
listWidget.add(
Row(
children: <Widget>[
Checkbox(
value: listBool[listLength],
onChanged: (bool newValue) {
setState(() {
print(newValue);
print(listBool[listLength]);
listBool[listLength] = newValue;
});
}),
text,
],
),
);
setState(() {});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('toDoList'),
backgroundColor: Colors.teal,
),
body: SafeArea(
child: Column(
children: <Widget>[
Row(
children: <Widget>[
Container(
height: 100,
width: 100,
color: Colors.red,
),
Container(
width: 100,
height: 100,
color: Colors.blue,
),
],
),
Expanded(
child: ListView.builder(
itemCount: listWidget.length,
itemBuilder: (BuildContext ctxt, int index) {
return listWidget[index];
})),
FloatingActionButton(
child: Icon(Icons.add),
onPressed: () => addList(Text('shopping')),
)
],
),
),
),
);
}
}
请检查以下代码并检查输出
import 'package:flutter/material.dart';
class FirstPage extends StatefulWidget {
@override
_FirstPageState createState() => _FirstPageState();
}
class _FirstPageState extends State<FirstPage> {
List<bool> listBool = [];
List<Widget> listWidget = [];
void addList() {
setState(() {
listBool.add(false);
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('toDoList'),
backgroundColor: Colors.teal,
),
body: SafeArea(
child: Column(
children: <Widget>[
Row(
children: <Widget>[
Container(
height: 100,
width: 100,
color: Colors.red,
),
Container(
width: 100,
height: 100,
color: Colors.blue,
),
],
),
Expanded(
child: ListView.builder(
itemCount: listBool.length,
itemBuilder: (BuildContext ctxt, int index) {
return Row(
children: <Widget>[
Checkbox(
value: listBool[index],
onChanged: (bool newValue) {
setState(() {
print(newValue);
print(listBool[index]);
listBool[index] = newValue;
});
}),
Text('shopping'),
],
);
})),
FloatingActionButton(
child: Icon(Icons.add),
onPressed: () => addList(),
)
],
),
),
),
);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.