Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Archives
Today
Total
05-16 04:51
관리 메뉴

nomad-programmer

[Programming/Flutter] TextFormField 위젯 본문

Programming/Flutter

[Programming/Flutter] TextFormField 위젯

scii 2020. 10. 11. 19:56

Form과 TextFormField를 사용하면 회원 가입처럼 사용자 입력값을 검증해야 할 때 유용하다.

TextFormField 위젯은 TextField 위젯이 제공하는 기능에 추가로 validator 프로퍼티를 활용한 검증 기능을 제공한다. 검증에는 TextFormField 위젯을 사용하며, 검증할 내용 전체를 Form위젯으로 감싼다. Form 위젯에는 유니크한 (유일무이한) 키를 지정해야 하며 GlobalKey<FromState> 인스턴스를 키로 사용한다.

TextFormField 위젯에는 validator 프로퍼티가 있으며 여기에는 입력된 값을 인수(value)로 받는 함수를 작성한다. 또한 검증 로직을 작성하는데, 에러 메시지를 문자열로 반환하거나 null을 반환하여 검증이 통과되었음을 정의할 수 있다.

폼의 검증은 _formKey.currentState.validate()로 수행하며 true 또는 false 값을 반환한다. 폼 안에 TextFormField 위젯이 여러 개 있어도 이 한 줄로 검증을 체크할 수 있다.

TextFormField 위젯은 TextField 위젯과 모양과 기능이 동일하지만 validator 프로퍼티를 추가로 가지고 있다. validator 프로퍼티에는 에러 메시지를 표시할 규칙을 함수로 작성할 수 있기 때문에 회원 가입 같은 폼에 사용하면 간단하게 입력값 검증을 할 수 있다.
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // primarySwatch: Colors.blue,
        brightness: Brightness.dark,
        primaryColor: Colors.lightBlue[800],
        accentColor: Colors.cyan[600],
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: BmiMain(),
    );
  }
}

class BmiMain extends StatefulWidget {
  @override
  _BmiMainState createState() => _BmiMainState();
}

class _BmiMainState extends State<BmiMain> {
  // 폼의 상태를 얻기 위한 키
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();

  //
  TextEditingController _emailController = new TextEditingController();
  TextEditingController _pwController = new TextEditingController();

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('텍스트 폼 필드 위젯 테스트'),
      ),
      body: Container(
        padding: const EdgeInsets.all(16.0),
        child: Form(
          // 키 할당
          key: _formKey,
          child: Column(
            children: <Widget>[
              TextFormField(
                controller: _emailController,
                validator: (value) {
                  // trim : 앞뒤 공백 제거
                  if (value.trim().isEmpty) {
                    return '이메일을 입력하세요.';
                  }
                  return null;
                },
                // 외곽선이 있고, 힌트 텍스트 표시
                decoration: InputDecoration(
                  border: OutlineInputBorder(),
                  hintText: 'ex) 이메일 입력',
                ),
                // 숫자만 입력할 수 있다.
                keyboardType: TextInputType.emailAddress,
              ),
              SizedBox(
                height: 16.0,
              ),
              TextFormField(
                controller: _pwController,
                validator: (value) {
                  if (value.trim().isEmpty) {
                    return '비밀번호를 입력하세요.';
                  }
                  return null;
                },
                decoration: InputDecoration(
                  border: OutlineInputBorder(),
                  hintText: 'ex) 비밀번호 입력',
                ),
                keyboardType: TextInputType.number,
              ),
              Container(
                margin: const EdgeInsets.only(top: 16.0),
                alignment: Alignment.centerRight,
                child: RaisedButton(
                  onPressed: () {
                    // 폼에 입력된 값 검증
                    if (_formKey.currentState.validate()) {
                      Navigator.push(
                        context,
                        MaterialPageRoute(builder: (context) => Page2()),
                      );
                    }
                  },
                  child: Text('로그인'),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

class Page2 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('페이지 2'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Container(
              color: Colors.red,
              width: 300,
              height: 300,
            ),
            Container(
              color: Colors.blue,
              width: 300,
              height: 300,
            ),
          ],
        ),
      ),
    );
  }
}

TextFormField 위젯을 활용한 예제 실행 모습

  • Form, TextFormField, GlobalKey를 사용하면 입력 폼의 에러를 간단히 검증할 수 있다.
  • TextFormField 위젯은 TextField 위젯의 기능에 추가로 오류 검증 로직을 추가할 수 있는 위젯이다.
  • TextFormField나 TextField 위젯에 입력된 값을 활용하려면 TextEditingController 클래스를 사용한다.
Comments