LoginSignup
0
0

【Flutter】フォームバリデーションとユーザー入力

Last updated at Posted at 2023-12-12

chatGPT に立ててもらったスケジュールに準じてFlutterの状態管理を勉強。

  • Day 7: フォームバリデーションとユーザー入力

フォームのバリデーションとサブミットの処理

  1. Formウィジェットでフォームをラップする
    • Formウィジェットを使用してフォームをラップする。
    • これにより、フォーム内のフィールドが連携して動作し、バリデーションが可能になる。
  2. TextFormFieldを使用して入力フィールドを作成する
    • TextFormFieldウィジェットは、ユーザーがテキストを入力できるフィールドを作成する。
    • validatorプロパティを使用してバリデーションロジックを指定する。
  3. バリデーションロジックの定義
    • validatorプロパティで指定した関数が、ユーザーが入力した内容の妥当性を検証する。不正な場合はエラーメッセージを返すことができる。
    • 例:入力されてなくて空だったら「入力してください」を返す
  4. Formのサブミット処理の実装
    • 通常、Form内に配置された「Submit」ボタンなどが押されたときに、Formウィジェット内のonSavedプロパティに指定した関数が呼び出され、フォームのデータを処理する。
サンプルソース
import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyForm(),
    );
  }
}

class MyForm extends StatefulWidget {
  @override
  _MyFormState createState() => _MyFormState();
}

class _MyFormState extends State<MyForm> {
  final _formKey = GlobalKey<FormState>(); // フォームの状態を管理するキー
  String _name = '';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Form Validation'),
      ),
      body: Form( // `Form`ウィジェットでフォームをラップする
        key: _formKey, // keyを割り当てる
        child: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            children: [
              // テキスト入力フィールド
              TextFormField(
                decoration: InputDecoration(labelText: '名前'),
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return '文字を入力してください';
                  }
                  return null; // バリデーション成功
                },
                onSaved: (value) {
                  _name = value!;
                },
              ),
              SizedBox(height: 16.0), // ボタンとフォームの間に空白
              // サブミットボタン
              ElevatedButton(
                onPressed: () {
                  // フォームのバリデーションを実行
                  if (_formKey.currentState!.validate()) {
                    // バリデーション成功の場合、onSavedが呼ばれる
                    _formKey.currentState!.save();
                    // ここでデータを送信するなどの処理を行う
                    ScaffoldMessenger.of(context).showSnackBar(
                    SnackBar(content: Text('名前: $_name'),), // 下から入力した文字出てくるよ
                  );
                  }
                },
                child: Text('Submit'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

0
0
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
0
0