gpt4 book ai didi

flutter : Boolean value in Checkbox doesn't change

转载 作者:行者123 更新时间:2023-12-01 21:46:57 26 4
gpt4 key购买 nike

我想建立一个复选框列表,当我按下添加按钮时它会增加。但是复选框不起作用,所以我在复选框中打印 onChanged 的​​ bool 值和复选框的值,我发现除了第一次按下(复选框仍然不起作用)之外,两者都是相同的。我将复选框的值更改为“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(),
)
],
),
),
),
);
}
}

关于 flutter : Boolean value in Checkbox doesn't change,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60312172/

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