[英]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.