我正在为我的自定义表单使用FLUTTER_FORM_BUILDER包。我使用 FormBuilderCheckbox 构建复选框列表,我使用构造函数为其赋予初始值initialValue
。当我尝试清除复选框时会出现问题。我使用 globalkey.currentState.reset() 来重置值。它确实重置了复选框的内部值,但似乎复选框仍处于选中状态。
我怎样才能清除它?我不能使用 .clear(),因为我不能将控制器分配给 FormBuilderCheckbox。
任何见解将不胜感激,谢谢。
编辑:这是一个简化的重现代码。
import 'package:flutter/material.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
Map _initialData = {
'checkbox': ['1'],
};
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyCustomForm(data: _initialData),
);
}
}
class MyCustomForm extends StatefulWidget {
final Map data;
const MyCustomForm({Key key, @required this.data}) : super(key: key);
@override
_MyCustomFormState createState() => _MyCustomFormState();
}
class _MyCustomFormState extends State<MyCustomForm> {
List _checkboxInitial;
final GlobalKey<FormBuilderState> _fbKey = GlobalKey<FormBuilderState>();
@override
void initState() {
setState(() {
_checkboxInitial = List.from(widget.data['checkbox']);
});
super.initState();
}
@override
Widget build(BuildContext context) {
return Material(
child: Container(
height: 200,
width: 200,
child: FormBuilder(
key: _fbKey,
child: Column(
children: <Widget>[
FormBuilderCheckboxList(
initialValue: _checkboxInitial,
decoration: InputDecoration(border: InputBorder.none),
attribute: 'checkbox',
options: [
'1',
'2',
'3',
]
.map(
(data) => FormBuilderFieldOption(
child: Text(data),
value: data,
),
)
.toList(growable: false),
),
RaisedButton(
onPressed: () {
setState(() {
_fbKey.currentState.reset();
});
},
child: Text('Clear'),
),
],
),
),
),
);
}
}