0
0
Fluttermobile~20 mins

TextFormField in Flutter - Mini App: Build & Ship

Choose your learning style9 modes available
Build: Simple Form Screen
This screen lets the user enter their name using a text input field and submit it. It validates that the name is not empty.
Target UI
-------------------------
| Simple Form Screen    |
|-----------------------|
| Name: [___________]   |
|                       |
|       [Submit]         |
-------------------------
Add a TextFormField for user to enter their name
Validate that the name is not empty when submitting
Show an error message below the field if empty
Add a Submit button that triggers validation
If valid, show a simple dialog with the entered name
Starter Code
Flutter
import 'package:flutter/material.dart';

class SimpleFormScreen extends StatefulWidget {
  @override
  State<SimpleFormScreen> createState() => _SimpleFormScreenState();
}

class _SimpleFormScreenState extends State<SimpleFormScreen> {
  final _formKey = GlobalKey<FormState>();
  final _nameController = TextEditingController();

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Simple Form Screen')),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Form(
          key: _formKey,
          child: Column(
            children: [
              // TODO: Add TextFormField here
              // TODO: Add Submit button here
            ],
          ),
        ),
      ),
    );
  }
}
Task 1
Task 2
Task 3
Task 4
Solution
Flutter
import 'package:flutter/material.dart';

class SimpleFormScreen extends StatefulWidget {
  @override
  State<SimpleFormScreen> createState() => _SimpleFormScreenState();
}

class _SimpleFormScreenState extends State<SimpleFormScreen> {
  final _formKey = GlobalKey<FormState>();
  final _nameController = TextEditingController();

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

  void _submit() {
    if (_formKey.currentState!.validate()) {
      showDialog(
        context: context,
        builder: (context) => AlertDialog(
          title: Text('Hello'),
          content: Text('Your name is: ${_nameController.text}'),
          actions: [
            TextButton(
              onPressed: () => Navigator.of(context).pop(),
              child: Text('OK'),
            ),
          ],
        ),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Simple Form Screen')),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Form(
          key: _formKey,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              TextFormField(
                controller: _nameController,
                decoration: InputDecoration(
                  labelText: 'Name',
                  border: OutlineInputBorder(),
                ),
                validator: (value) {
                  if (value == null || value.trim().isEmpty) {
                    return 'Please enter your name';
                  }
                  return null;
                },
              ),
              SizedBox(height: 20),
              Center(
                child: ElevatedButton(
                  onPressed: _submit,
                  child: Text('Submit'),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

We use a Form widget with a GlobalKey to manage validation. The TextFormField has a validator function that checks if the input is empty and returns an error message if so. The Submit button calls _formKey.currentState!.validate() to trigger validation. If valid, it shows a dialog with the entered name. We also use a TextEditingController to get the text input value.

Final Result
Completed Screen
-------------------------
| Simple Form Screen    |
|-----------------------|
| Name: [John Doe    ]  |
|                       |
|       [Submit]         |
-------------------------
User types their name in the text field
If user taps Submit with empty field, error message appears below the field
If user taps Submit with valid name, a dialog pops up showing 'Your name is: [name]'
User can close the dialog by tapping OK
Stretch Goal
Add a Clear button that clears the text field when tapped
💡 Hint
Add an IconButton inside the TextFormField's suffixIcon that calls _nameController.clear()