【バリデーション】Dart / Flutterでフォームの入力チェックをする方法

フォームのキーを作る

final _formKey = GlobalKey<FormState>();

フォームを作成する

フォームのキーを指定して、
あとは、HTMLのように中に入力やサブミットボタンを入れる

Form(
  key: _formKey,
  child: Column(
    children: <Widget>[
      // 入力欄、ボタンを入れる
    ],
  ),
);

入力欄

TextFormField(
  // The validator receives the text that the user has entered.
  validator: (value) {
    if (value == null || value.isEmpty) {
      return '入力されていません!';
    }
    return null;
  },
),

サブミットボタン

ElevatedButton(
  onPressed: () {
    // Validate returns true if the form is valid, or false otherwise.
    if (!_formKey.currentState!.validate()) {
      // If the form is valid, display a snackbar. In the real world,
      // you'd often call a server or save the information in a database.
      ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
        content: Text('入力内容に足りない項目があります'),
        backgroundColor: Colors.red,
      ));
    }
  },
  child: const Text('Submit'),
),

Flutter開発で知らないと損すること Flutter開発で知らないと損すること

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です