0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

FlutterのTextFormFieldの基本的な使い方

Posted at

普段あまりFlutterは使わないのでメモ。

主な実装手順(私流)

  • decorationを設定してまず見た目を整える。
  • validatorを設定してバリデーションの条件を設定。
  • validatorの設定だけだと_formKey.currentSate!.validate()実行時だけなので、
      - autovalidateMode: AutovalidateMode.onUserInteraction とする
  • 値を取得するために、controllerを設定(disposeを忘れずに)

onChangeとかは特にいじらなくても大丈夫っぽい。

その他

  • 環境依存だが、Formの上位にPaddingを設定するのが便利。

Validation実装時はTextFormFieldを使うのが楽。

完成イメージ

いちおうこんな感じ。
とりあえずEmailだけだが、childrenにいろいろ足せば直ぐに追加可能(controllerも追加)。

本来Formだけでいいが、実務では上部に何か配置することになるので、その典型的な方法も調べておく。

実装

main.dart
import 'package:flutter/material.dart';

void main() {
  runApp(const MainApp());
}

class MainApp extends StatelessWidget {
  const MainApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(home: BasicFormScreen());
  }
}

class BasicFormScreen extends StatefulWidget {
  @override
  _BasicFormState createState() => _BasicFormState();
}

class _BasicFormState extends State<BasicFormScreen> {
  final _formKey = GlobalKey<FormState>();

  final _emailController = TextEditingController();

  @override
  void dispose() {
    _emailController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          Container(
            width: double.infinity,
            height: 120,
            color: Color(0xFFAAAAAA),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [SizedBox(height: 40), Text("入力フォーム")],
            ),
          ),
          Padding(
            padding: EdgeInsets.all(30.0),
            child: Form(
              key: _formKey,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: [
                  TextFormField(
                    decoration: InputDecoration(
                      labelText: "Email",
                      border: OutlineInputBorder(),
                    ),
                    validator: (value) {
                      if (value == null || value.isEmpty) {
                        return "Emailは必須です。";
                      }
                      final emailRegex = RegExp(r'^[^@\s]+@[^@\s]+\.[^@\s]+$');
                      if (!emailRegex.hasMatch(value)) {
                        return "Emailを正しい形式で入力してください。";
                      }
                      return null;
                    },
                    autovalidateMode: AutovalidateMode.onUserInteraction,
                    controller: _emailController,
                  ),
                  SizedBox(height: 20),
                  ElevatedButton(
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Color(0xFF333333),
                      foregroundColor: Colors.white,
                    ),
                    onPressed: () {
                      if (_formKey.currentState!.validate()) {
                        debugPrint('Email: ${_emailController.text}');
                      }
                    },
                    child: Text("送信"),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
}

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?