LoginSignup
15
8

More than 5 years have passed since last update.

TextFormFieldのvalidatorが動作しない

Last updated at Posted at 2019-01-15

超初歩的な内容かと思いますが、ハマったので記録しておきます。
変な先入観は注意ですね。:cry:

問題

下記コードで、validatorに設定した関数が呼び出されない。

import 'package:flutter/material.dart';

class HogeState extends State<Hoge> {

  final _formKey = GlobalKey<FormState>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Form(
          key: _formKey,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              TextFormField(
                keyboardType: TextInputType.number,
                validator: (value) {
                  print("onValid");// ここが動作しない
                },
              ),
              RaisedButton(
                onPressed: () {
                  print("onPressed");
                },
                child: Text('Button'),
              )
            ],
          ),
        )
    );
  }
}

解決方法

ボタンのonPressed内でvalidateを呼び出す必要があった。
または、TextFormFieldのautovalidate引数をtrueに設定する。

onPressed: () {
  if (_formKey.currentState.validate()) {
    _formKey.currentState.save();// TextFormFieldのonSavedが呼び出される
  }
}

参考

公式サイトにしっかり書いてあります。

15
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
8