我想建立一个复选框列表,当我按下添加按钮时,该列表会增加。 但是复选框不起作用,因此我在复选框中打印了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')),
)
],
),
),
),
);
}
}
答案 0 :(得分:5)
请检查下面的代码并检查输出
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(),
)
],
),
),
),
);
}
}