CodeBlanks Logo Icon CodeBlanks

Summary - Form validation

Combine Form, validator and onSaved to make an input form.

Summary - Form validation

In this section you learned three things: with Form you group fields and access state via GlobalKey<FormState>; with validator you check field validity and show error messages; with onSaved you collect field values during save.

if (_formKey.currentState!.validate()) {
  _formKey.currentState!.save();
  print('name: $_name');
}

Combining these, you build a login form.

Practice Build a login form

In Ekrani stateful widget, declare _formKey and _eposta. Place a TextFormField inside a Form; the validator should return 'E-posta gerekli' for empty value, and onSaved should assign the value to _eposta. On button press, if validate succeeds, call save and print 'eposta: $_eposta'. In main, call print('giriş formu').

Starter code

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

void main() {
  print('giriş formu');
  runApp(MaterialApp(home: Ekrani()));
}

class Ekrani extends StatefulWidget {
  @override
  _EkraniState createState() => _EkraniState();
}

class _EkraniState extends State<Ekrani> {
  // _formKey ve _eposta ekle

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Padding(
        padding: EdgeInsets.all(16),
        child: Form(
          key: _formKey,
          child: Column(
            children: [
              // validator ve onSaved ile TextFormField ekle
              TextFormField(),
              ElevatedButton(
                onPressed: () {
                  // validate ve save çağır
                },
                child: Text('Giriş'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

Sample solution

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

void main() {
  print('giriş formu');
  runApp(MaterialApp(home: Ekrani()));
}

class Ekrani extends StatefulWidget {
  @override
  _EkraniState createState() => _EkraniState();
}

class _EkraniState extends State<Ekrani> {
  final _formKey = GlobalKey<FormState>();
  String? _eposta;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Padding(
        padding: EdgeInsets.all(16),
        child: Form(
          key: _formKey,
          child: Column(
            children: [
              TextFormField(
                validator: (deger) {
                  if (deger!.isEmpty) {
                    return 'E-posta gerekli';
                  }
                  return null;
                },
                onSaved: (deger) {
                  _eposta = deger;
                },
              ),
              ElevatedButton(
                onPressed: () {
                  if (_formKey.currentState!.validate()) {
                    _formKey.currentState!.save();
                    print('eposta: $_eposta');
                  }
                },
                child: Text('Giriş'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

Expected output

giriş formu

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What should be done first when the user presses the 'Login' button in the login form?

  • Close the app
  • Clear the form fields
  • Navigate immediately
  • Validate the form with _formKey.currentState!.validate() Correct answer

Explanation: When the login button is pressed, the form is first validated with _formKey.currentState!.validate(); if successful, save is called and values are collected.

2 Complete the Form key type

Question
final _formKey = GlobalKey<____>();
Answer
final _formKey = GlobalKey<FormState>();

Explanation: The Form widget's key must be of type GlobalKey<FormState>; this provides access to validate and save methods.

3 Form validation parts

Term Meaning
Form Widget grouping form fields
validator Callback checking field validity
onSaved Collects value during save
validate Validation method called on FormState

All lessons in Intermediate