我正在 AlertDialog 中做一个复选框。我希望用户在上传之前勾选复选框。我的问题是,如果我将变量设置为 false ,复选框将不会更改为 true 或更改回 false。这是我的代码:
bool _isChecked = false;
List<String> _texts = [
"I have confirm the data is correct",
"I have agreed to terms and conditions.",
];
showConfirmationDialog(BuildContext context){
AlertDialog alert=AlertDialog(
title: Text('Confirmation'),
content:
ListView(
padding: EdgeInsets.all(8.0),
children: _texts.map((text) => CheckboxListTile(
title: Text(text),
value: _isChecked,
onChanged: (val) {
setState(() {
_isChecked = val;
});
},
)).toList(),
),
actions: <Widget>[
SizedBox(
width: 300,
child:RaisedButton(
color: Colors.blue,
onPressed: () => upload(context),
child:Text('Upload'),
)
)
],
);
showDialog(barrierDismissible: false,
context:context,
builder:(BuildContext context){
return alert;
},
);
}
Run Code Online (Sandbox Code Playgroud)
谁能帮我?
您需要有状态的小部件,因为 showDialog 无法更改状态。
下面的代码可以帮助您了解更多。
class DeleteWidget extends StatefulWidget {
@override
_DeleteWidgetState createState() => _DeleteWidgetState();
}
class _DeleteWidgetState extends State<DeleteWidget> {
var currentSection;
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: RaisedButton(
onPressed: () {
showConfirmationDialog(context);
},
child: Text("data"),
),
),
),
);
}
showConfirmationDialog(BuildContext context) {
showDialog(
barrierDismissible: false,
context: context,
builder: (BuildContext context) {
return CustomDialog();
},
);
}
}
class CustomDialog extends StatefulWidget {
@override
_CustomDialogState createState() => _CustomDialogState();
}
class _CustomDialogState extends State<CustomDialog> {
List<bool> _isChecked = [false, false];
bool canUpload = false;
List<String> _texts = [
"I have confirm the data is correct",
"I have agreed to terms and conditions.",
];
@override
Widget build(BuildContext context) {
return AlertDialog(
title: Text('Confirmation'),
content: Container(
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Expanded(
child: ListView(
shrinkWrap: true,
padding: EdgeInsets.all(8.0),
children: [
ListView.builder(
shrinkWrap: true,
itemCount: _texts.length,
itemBuilder: (_, index) {
return CheckboxListTile(
title: Text(_texts[index]),
value: _isChecked[index],
onChanged: (val) {
setState(() {
_isChecked[index] = val;
canUpload = true;
for (var item in _isChecked) {
if (item == false) {
canUpload = false;
}
}
});
},
);
},
),
]),
),
],
),
),
actions: <Widget>[
SizedBox(
width: 300,
child: RaisedButton(
color: Colors.blue,
onPressed: canUpload
? () {
print("upload");
}
: null,
child: Text('Upload'),
))
],
);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6959 次 |
| 最近记录: |