我想验证包含在脚手架中的bottomSheet内部的表单。
问题是当我关闭bottomSheet并单击“保存”(在AppBar中)时。
似乎最终形式= _formAddPlayerKey.currentState;当bottomSheet关闭时,返回null。
当bottomSheet打开时,我可以验证表单。
我的代码,一个内部带有bottomSheet的脚手架:
return Scaffold(
key: _scaffoldKey,
appBar: AppBar(
title: Text('MyTitle'),
actions: <Widget>[
//--- Form validation
FlatButton(
onPressed: () {
final form = _formAddPlayerKey.currentState;
if (form.validate()) {
form.save();
print('SAV OK!!!');
}
},
child: Text(
'SAVE',
style: Theme.of(context)
.textTheme
.subhead
.copyWith(color: Colors.white),
),
)
],
),
floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
floatingActionButton:
showFab
? FloatingActionButton(
child: const Icon(Icons.comment, color: Colors.white),
onPressed: () {
var bottomSheetController =
_scaffoldKey.currentState.showBottomSheet(
(context) => Container(
color: Colors.pink.withOpacity(
0.2), //Theme.of(context).accentColor.withOpacity(0.5),
//backgroundColor: Theme.of(context).accentColor.withOpacity(0.5),
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
child: Form(
key: _formAddPlayerKey,
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
SizedBox(
height: 10,
),
Container(
color: Colors.white.withOpacity(0.5),
//Colors.white,
margin: EdgeInsets.all(16.0),
child: TextFormField(
maxLines: 4,
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 30,
),
decoration: InputDecoration(
hoverColor: Colors.white,
fillColor: Colors.white,
labelText: 'Observation',
border: OutlineInputBorder(),
prefixIcon: Icon(Icons.note),
),
keyboardType: TextInputType.text,
initialValue:
'My observation....',
validator: (value) {
return validateMyValue(value);
},
onSaved: (value) =>
_MyValue = value,
),
),
],
),
),
),
);
showFoatingActionButton(false);
/// close ?
bottomSheetController.closed.then((value) {
showFoatingActionButton(true);
});
})
: Container(),
bottomNavigationBar: _buildBottomNavigationBar(context),
body: _buildBody(context),
);
}
void showFoatingActionButton(bool value) {
setState(() {
showFab = value;
});
}
答案 0 :(得分:0)
只需在State类中全局定义表单键
var _formAddPlayerKey = GlobalKey<FormState>();
每当您想使用相应的密钥来验证表单时,只需键入此内容,
bool validate = _formAddPlayerKey.currentState.validate();
如果布尔变量validate为true,则您的表单符合标记,如果验证失败,它将自动设置您已在TextFormField小部件的validate属性中定义的错误消息