我在AlertDialog中使用CheckboxListTile时遇到了一些问题。问题是,当我尝试勾选时,这个框不能正常工作。这是我的代码:
import 'package:flutter/material.dart';
void main() {
runApp(PadelApp());
}
class PadelApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false, //esto es para quitar el cartelito de debug
title: 'Test',
theme: ThemeData( primarySwatch: Colors.blue),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget{
//@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage>{
var _formkey = GlobalKey<FormState>();
var _lstgrupos = ['Group 1', 'Group 2'];
List<String> _SelectedGroupsItems = [];
String _SelectedGroups = 'Groups';
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Test')),
body: Form(
key: _formkey,
child: Padding(
padding: const EdgeInsets.all(10.0),
child: ListView(
children: <Widget>[
Row(
children: <Widget>[
Expanded(
child: ListTile(
title: Text(_SelectedGroups),
onTap: () => showDialog(
context: context,
barrierDismissible: true,
builder: (context) {
return AlertDialog(
title: Text("Choose a group"),
content: SingleChildScrollView(
child: Container(
width: double.infinity,
child: Column(
mainAxisSize: MainAxisSize.min,
children: _lstgrupos.map((lst) => CheckboxListTile(
title: Text(lst),
value:_SelectedGroupsItems.contains(lst),
onChanged: (value) {
setState(() {
if (value!) {
if (!_SelectedGroupsItems.contains(lst)) {
_SelectedGroupsItems.add(lst);
}
} else {
if (_SelectedGroupsItems.contains(lst)) {
_SelectedGroupsItems.add(lst);
}
}
});
},
)).toList(),
),
),
),
actions: <Widget>[
TextButton(
child: Text('Cerrar'),
onPressed: ()=> Navigator.of(context).pop(),
)
]
);
}
),
),
),
],
),
],
),
),
),
);
}
}
我试着用几种方法修改,但我意识到问题出在"价值"上。变量(in onChanged: (value))。该变量总是为真或总是为假,但不会改变。
你需要用statfullbuilder包围AlertDialog否则setState不会重建对话框像这样:
StatefulBuilder(
builder: (context, setState) {
return AlertDialog(...)
})