블로그

[Flutter] 플루터 폼 밸리데이션 (form validation)

플루터에서 form 을 이용한 validation 예제입니다.

폼의 상태를 저장하는 변수를 선언합니다.

final _formKey = GlobalKey<FormState>();

Form 컴포넌트를 사용해서 폼을 정의하고 입력 필드들을 Form 안에 배치합니다.

    Widget HomePageBody() {
        return Container(
            padding: EdgeInsets.all(16),
            child: Form(
                key: _formKey,
                child: SingleChildScrollView(
                    child: Column(
                        children: <Widget>[
                            UserIdInput(),
                            SizedBox(height: 16,),
                            PasswordInput(),
                            SizedBox(height: 16,),
                            SubmitButton()
                        ],
                    ),
                ),
            ),
        );
    }

입력필드의 validator 속성에 밸리데이션 로직을 구현합니다.

    Widget UserIdInput() {
        return TextFormField(
            focusNode: _user_idFocusNode,
            autofocus: true,
            textCapitalization: TextCapitalization.words,
            keyboardType: TextInputType.text ,
            decoration: InputDecoration(
                labelText: "아이디",
            ),
            textInputAction: TextInputAction.next,
            validator: (name) {
                if (name.isEmpty) {
                    return '아이디를 입력하세요.';
                }
                return null;

            },
            onSaved: (name)=> _user_id = name,
            onFieldSubmitted: (_){
                fieldFocusChange(context, _user_idFocusNode, _emailFocusNode);
            },
        );
    }

폼키의 validate() 메소드로 입력 필드의 값들을 검증합니다.

    RaisedButton SubmitButton(){
        return  RaisedButton(
            color:Theme.of(context).primaryColor,
            onPressed: (){
                if(_formKey.currentState.validate()){
                    _formKey.currentState.save();
                }
            },
            child: Text("Submit",style: TextStyle(color: Colors.white),),
        );
    }

밸리데이션시 나타나는 메시지들입니다. 기본적으로 입력필드 아래에 표시됩니다.

flutter form validation

아래는 전체 소스입니다.

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

class LoginPage extends StatefulWidget {
    @override
    _LoginPageState createState() {
        return _LoginPageState();
    }
}

class _LoginPageState extends State<LoginPage> {
    String _user_id, _password= "";

    final _formKey = GlobalKey<FormState>();

    FocusNode _user_idFocusNode = FocusNode();
    FocusNode _emailFocusNode = FocusNode();
    FocusNode _passwordFocusNode = FocusNode();

    @override
    Widget build(BuildContext context) {
        return Scaffold(
            appBar: AppBar(title: Text("로그인"),),
            body: HomePageBody(),
        );
    }

    Widget HomePageBody() {
        return Container(
            padding: EdgeInsets.all(16),
            child: Form(
                key: _formKey,
                child: SingleChildScrollView(
                    child: Column(
                        children: <Widget>[
                            UserIdInput(),
                            SizedBox(height: 16,),
                            PasswordInput(),
                            SizedBox(height: 16,),
                            SubmitButton()
                        ],
                    ),
                ),
            ),
        );
    }

    Widget UserIdInput() {
        return TextFormField(
            focusNode: _user_idFocusNode,
            autofocus: true,
            textCapitalization: TextCapitalization.words,
            keyboardType: TextInputType.text ,
            decoration: InputDecoration(
                labelText: "아이디",
            ),
            textInputAction: TextInputAction.next,
            validator: (name) {
                if (name.isEmpty) {
                    return '아이디를 입력하세요.';
                }
                return null;

            },
            onSaved: (name)=> _user_id = name,
            onFieldSubmitted: (_){
                fieldFocusChange(context, _user_idFocusNode, _emailFocusNode);
            },
        );
    }

    Widget PasswordInput() {
        return TextFormField(
            focusNode: _passwordFocusNode,
            keyboardType: TextInputType.text ,
            obscureText: true,
            decoration: InputDecoration(
                labelText: "비밀번호",
                suffixIcon: Icon(Icons.lock),
            ),
            textInputAction: TextInputAction.done,

            validator: (password) {
                if (password.isEmpty) {
                    return '비밀번호를 입력하세요.';
                }
                return null;
            },
            onSaved: (password)=> _password = password,
        );
    }

    RaisedButton SubmitButton(){
        return  RaisedButton(
            color:Theme.of(context).primaryColor,
            onPressed: (){
                if(_formKey.currentState.validate()){
                    _formKey.currentState.save();
                }
            },
            child: Text("Submit",style: TextStyle(color: Colors.white),),
        );
    }