class MyCustomFormState extends State<MyCustomForm>{ final _formKey = GlobalKey<FormState>(); @override Widget build(BuildContext context){ return Form( key: _formKey, child: Column( crossAxisAlignment: CrossAxisAlignment.center, children: [ TextFormField( validator: (value){ if(value == null || value.isEmpty){ return 'テキストを入力してください'; } }, ), Padding( padding: const EdgeInsets.symmetric(vertical: 16.0), child: ElevatedButton( onPressed:() { if(_formKey.currentState!.validate()){ ScaffoldMessenger.of(context).showSnackBar( const SnackBar(content: Text('送信完了')), ); } }, child: const Text('送信'), ) ) ] ) ); } }
フォームを一意に認識するためのキー
final _formKey = GlobalKey<FormState>();
Form( key: _formKey, )
入力がない場合テキストを返す
if (_formKey.currentState!.validate()) { ScaffoldMessenger.of(context).showSnackBar( const SnackBar(content: Text('送信完了')), ); }