Bird
Raised Fist0
Fluttermobile~20 mins

Form widget and GlobalKey in Flutter - Mini App: Build & Ship

Choose your learning style10 modes available
Build: Simple Login Form
A login screen with a form that validates user input using a GlobalKey.
Target UI
-------------------------
| Simple Login Form      |
|-----------------------|
| Email: [___________]  |
| Password: [_______]   |
|                       |
|       [Login]         |
-------------------------
Use a Form widget with a GlobalKey to manage form state.
Include two TextFormFields: one for email and one for password.
Validate email to check if it contains '@' and is not empty.
Validate password to ensure it is at least 6 characters.
Add a Login button that triggers validation and shows a SnackBar on success.
Starter Code
Flutter
import 'package:flutter/material.dart';

class LoginFormScreen extends StatefulWidget {
  @override
  State<LoginFormScreen> createState() => _LoginFormScreenState();
}

class _LoginFormScreenState extends State<LoginFormScreen> {
  final _formKey = GlobalKey<FormState>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Simple Login Form')),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Form(
          key: _formKey,
          child: Column(
            children: [
              // TODO: Add email TextFormField here
              // TODO: Add password TextFormField here
              SizedBox(height: 20),
              ElevatedButton(
                onPressed: () {
                  // TODO: Add form validation and SnackBar here
                },
                child: Text('Login'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
Task 1
Task 2
Task 3
Task 4
Solution
Flutter
import 'package:flutter/material.dart';

class LoginFormScreen extends StatefulWidget {
  @override
  State<LoginFormScreen> createState() => _LoginFormScreenState();
}

class _LoginFormScreenState extends State<LoginFormScreen> {
  final _formKey = GlobalKey<FormState>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Simple Login Form')),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Form(
          key: _formKey,
          child: Column(
            children: [
              TextFormField(
                decoration: InputDecoration(labelText: 'Email'),
                keyboardType: TextInputType.emailAddress,
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return 'Please enter your email';
                  }
                  if (!value.contains('@')) {
                    return 'Enter a valid email';
                  }
                  return null;
                },
              ),
              TextFormField(
                decoration: InputDecoration(labelText: 'Password'),
                obscureText: true,
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return 'Please enter your password';
                  }
                  if (value.length < 6) {
                    return 'Password must be at least 6 characters';
                  }
                  return null;
                },
              ),
              SizedBox(height: 20),
              ElevatedButton(
                onPressed: () {
                  if (_formKey.currentState?.validate() ?? false) {
                    ScaffoldMessenger.of(context).showSnackBar(
                      SnackBar(content: Text('Login Successful!')),
                    );
                  }
                },
                child: Text('Login'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

This screen uses a Form widget with a GlobalKey to manage the form state. The TextFormField widgets each have a validator function that checks the input. The email field checks if the input is not empty and contains an '@' symbol. The password field checks if the input is not empty and has at least 6 characters.

When the Login button is pressed, the form is validated by calling _formKey.currentState?.validate(). If all validators return null (meaning valid), a SnackBar appears with a success message. This approach keeps validation logic clean and user feedback immediate.

Final Result
Completed Screen
-------------------------
| Simple Login Form      |
|-----------------------|
| Email: [user@example] |
| Password: [******]    |
|                       |
|       [Login]         |
-------------------------
User types email and password in the fields.
User taps Login button.
If inputs are invalid, error messages appear below fields.
If inputs are valid, a SnackBar shows 'Login Successful!'.
Stretch Goal
Add a 'Show Password' checkbox that toggles password visibility.
💡 Hint
Use a boolean state variable to control the obscureText property of the password TextFormField.

Practice

(1/5)
1. What is the main purpose of using a Form widget in Flutter?
easy
A. To group multiple input fields for validation and saving
B. To create a button that submits data
C. To display images in a grid layout
D. To manage app navigation between screens

Solution

  1. Step 1: Understand the role of Form widget

    The Form widget groups input fields so you can validate and save them together.
  2. Step 2: Compare options with Form's purpose

    Only To group multiple input fields for validation and saving describes grouping input fields for validation and saving, which is the Form's main use.
  3. Final Answer:

    To group multiple input fields for validation and saving -> Option A
  4. Quick Check:

    Form groups inputs = D [OK]
Hint: Form groups inputs for validation and saving [OK]
Common Mistakes:
  • Thinking Form is for navigation or layout
  • Confusing Form with buttons or images
  • Assuming Form manages app state globally
2. Which of the following is the correct way to declare a GlobalKey for a Form in Flutter?
easy
A. final _formKey = GlobalKey();
B. final _formKey = GlobalKey<FormState>();
C. final _formKey = GlobalKey<Form>();
D. final _formKey = GlobalKey<State>();

Solution

  1. Step 1: Identify correct GlobalKey type for Form

    The GlobalKey must be typed as GlobalKey<FormState> to access the Form's state.
  2. Step 2: Check each option's type

    final _formKey = GlobalKey<FormState>(); uses GlobalKey<FormState>(), which is correct. Others use wrong or incomplete types.
  3. Final Answer:

    final _formKey = GlobalKey<FormState>(); -> Option B
  4. Quick Check:

    GlobalKey typed as FormState = A [OK]
Hint: GlobalKey must be typed as GlobalKey<FormState>() [OK]
Common Mistakes:
  • Using GlobalKey without type parameter
  • Using GlobalKey<Form> instead of FormState
  • Using GlobalKey<State> which is too generic
3. Given this Flutter code snippet:
final _formKey = GlobalKey<FormState>();

Form(
  key: _formKey,
  child: TextFormField(
    validator: (value) => value!.isEmpty ? 'Enter text' : null,
  ),
);

// Later in code
if (_formKey.currentState!.validate()) {
  print('Valid input');
} else {
  print('Invalid input');
}
What will be printed if the TextFormField is empty when validate() is called?
medium
A. Valid input
B. No output, code throws error
C. Invalid input
D. Nothing happens, validate() returns null

Solution

  1. Step 1: Understand validator behavior

    The validator returns 'Enter text' if the field is empty, which means validation fails.
  2. Step 2: Check validate() result

    validate() returns false if any validator returns a non-null string, so the else branch runs.
  3. Final Answer:

    Invalid input -> Option C
  4. Quick Check:

    Empty input triggers validator error = B [OK]
Hint: Validator returns error string means validate() is false [OK]
Common Mistakes:
  • Assuming validate() returns true on empty input
  • Confusing validator return null with error
  • Thinking validate() throws error on empty input
4. Identify the error in this Flutter code snippet:
final _formKey = GlobalKey<FormState>();

Form(
  key: _formKey,
  child: TextFormField(
    validator: (value) {
      if (value!.length < 3) return 'Too short';
      return null;
    },
  ),
);

// Later
if (_formKey.currentState.validate()) {
  print('Valid');
}
medium
A. GlobalKey should be GlobalKey<Form>
B. Validator should return a boolean, not a string
C. Missing exclamation mark after currentState
D. Calling validate() without null check on currentState

Solution

  1. Step 1: Check usage of currentState

    currentState can be null if Form is not mounted, so calling validate() without null check risks error.
  2. Step 2: Review code for null safety

    The code calls _formKey.currentState.validate() without ! or ?. which causes a compile error in null-safe Dart.
  3. Final Answer:

    Calling validate() without null check on currentState -> Option D
  4. Quick Check:

    currentState may be null, needs ! or ? = A [OK]
Hint: Always null-check currentState before validate() [OK]
Common Mistakes:
  • Forgetting to add ! after currentState
  • Returning boolean from validator instead of string/null
  • Using wrong GlobalKey type
5. You want to create a form with two TextFormFields and a submit button. You want to validate both fields and show errors if empty. Which approach correctly uses GlobalKey and Form to achieve this?
hard
A. Declare a GlobalKey<FormState>, assign it to Form's key, use validators on fields, call _formKey.currentState!.validate() on submit
B. Use separate GlobalKeys for each TextFormField and call validate() on each key
C. Use a GlobalKey without type parameter and call validate() on it
D. Wrap each TextFormField in its own Form widget with separate GlobalKeys

Solution

  1. Step 1: Understand Form and GlobalKey usage

    One GlobalKey<FormState> is used to manage the whole Form and validate all fields together.
  2. Step 2: Evaluate options for best practice

    Declare a GlobalKey<FormState>, assign it to Form's key, use validators on fields, call _formKey.currentState!.validate() on submit correctly uses one GlobalKey<FormState>, assigns it to Form, uses validators, and calls validate() once.
  3. Final Answer:

    Declare a GlobalKey<FormState>, assign it to Form's key, use validators on fields, call _formKey.currentState!.validate() on submit -> Option A
  4. Quick Check:

    Single GlobalKey<FormState> for whole Form = C [OK]
Hint: Use one GlobalKey<FormState> for entire Form [OK]
Common Mistakes:
  • Using multiple GlobalKeys for each field
  • Not typing GlobalKey as FormState
  • Wrapping each field in separate Form widgets
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard