Bird
Raised Fist0
Fluttermobile~20 mins

Form submission in Flutter - Mini App: Build & Ship

Choose your learning style10 modes available
Build: Simple Form Screen
A screen with a form that lets users enter their name and email, then submit the form to see a confirmation message.
Target UI
Simple Form Screen

+---------------------------+
| Name: [______________]    |
| Email: [______________]   |
|                           |
|        [Submit]            |
+---------------------------+
Two TextFormFields: one for name, one for email
A Submit button below the fields
Validate that both fields are not empty
On submit, show a SnackBar with message 'Form submitted: [name], [email]'
Use a Form widget with a GlobalKey to manage validation
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();
  final _emailController = TextEditingController();

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

  void _submitForm() {
    // TODO: Add form validation and submission logic
  }

  @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: [
              TextFormField(
                controller: _nameController,
                decoration: InputDecoration(labelText: 'Name'),
                // TODO: Add validator
              ),
              SizedBox(height: 16),
              TextFormField(
                controller: _emailController,
                decoration: InputDecoration(labelText: 'Email'),
                // TODO: Add validator
              ),
              SizedBox(height: 32),
              ElevatedButton(
                onPressed: _submitForm,
                child: Text('Submit'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
Task 1
Task 2
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();
  final _emailController = TextEditingController();

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

  void _submitForm() {
    if (_formKey.currentState?.validate() ?? false) {
      final name = _nameController.text.trim();
      final email = _emailController.text.trim();
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('Form submitted: $name, $email')),
      );
    }
  }

  @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: [
              TextFormField(
                controller: _nameController,
                decoration: InputDecoration(labelText: 'Name'),
                validator: (value) {
                  if (value == null || value.trim().isEmpty) {
                    return 'Please enter your name';
                  }
                  return null;
                },
              ),
              SizedBox(height: 16),
              TextFormField(
                controller: _emailController,
                decoration: InputDecoration(labelText: 'Email'),
                validator: (value) {
                  if (value == null || value.trim().isEmpty) {
                    return 'Please enter your email';
                  }
                  return null;
                },
              ),
              SizedBox(height: 32),
              ElevatedButton(
                onPressed: _submitForm,
                child: Text('Submit'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

This solution uses a Form widget with a GlobalKey to manage the form state and validation.

Each TextFormField has a validator that checks if the input is empty and returns an error message if so.

The _submitForm method calls validate() on the form state. If validation passes, it shows a SnackBar with the entered name and email.

This approach keeps the UI responsive and provides immediate feedback to the user.

Final Result
Completed Screen
Simple Form Screen

+---------------------------+
| Name: [John Doe     ]     |
| Email: [john@example.com] |
|                           |
|        [Submit]            |
+---------------------------+
User types name and email in the fields
User taps Submit button
If fields are empty, error messages appear below each field
If fields are filled, a SnackBar appears at bottom: 'Form submitted: John Doe, john@example.com'
Stretch Goal
Add email format validation to the email field
💡 Hint
Use a simple RegExp to check if the email contains '@' and a dot '.' after it

Practice

(1/5)
1. What is the main purpose of using a Form widget in Flutter when collecting user input?
easy
A. To create animations for buttons
B. To display images inside the app
C. To group multiple input fields and manage their validation together
D. To handle network requests automatically

Solution

  1. Step 1: Understand the role of Form widget

    The Form widget groups input fields and helps manage their validation as a single unit.
  2. Step 2: Identify the correct purpose

    Other options describe unrelated features like images, animations, or network handling.
  3. Final Answer:

    To group multiple input fields and manage their validation together -> Option C
  4. Quick Check:

    Form groups inputs for validation = A [OK]
Hint: Form widget groups inputs for validation and submission [OK]
Common Mistakes:
  • Thinking Form handles images or animations
  • Confusing Form with network handling widgets
  • Ignoring validation grouping
2. Which of the following is the correct way to declare a GlobalKey for a form in Flutter?
easy
A. final _formKey = GlobalKey<State>();
B. final _formKey = GlobalKey();
C. final _formKey = GlobalKey<Form>();
D. final _formKey = GlobalKey<FormState>();

Solution

  1. Step 1: Recall the correct type for form key

    The form key must be typed as GlobalKey<FormState> to access form validation methods.
  2. Step 2: Check each option's type

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

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

    Form key type = GlobalKey<FormState> [OK]
Hint: Use GlobalKey<FormState> to manage form state [OK]
Common Mistakes:
  • Omitting <FormState> generic type
  • Using GlobalKey<Form> instead of FormState
  • Using untyped GlobalKey
3. Given this Flutter code snippet:
final _formKey = GlobalKey<FormState>();

Form(
  key: _formKey,
  child: TextFormField(
    validator: (value) {
      if (value == null || value.isEmpty) {
        return 'Enter text';
      }
      return null;
    },
  ),
);

// Later in button onPressed:
if (_formKey.currentState!.validate()) {
  print('Valid input');
} else {
  print('Invalid input');
}
What will be printed if the user submits the form with an empty text field?
medium
A. Invalid input
B. No output
C. Valid input
D. Runtime error

Solution

  1. Step 1: Analyze the validator function

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

    Since validator returns a non-null string, validate() returns false, triggering the else branch.
  3. Final Answer:

    Invalid input -> Option A
  4. Quick Check:

    Empty input fails validation = Invalid input [OK]
Hint: Validator returning non-null means invalid input [OK]
Common Mistakes:
  • Assuming empty input is valid
  • Confusing validator return values
  • Expecting no output on validation failure
4. Consider this Flutter code snippet for form submission:
final _formKey = GlobalKey<FormState>();

Form(
  key: _formKey,
  child: TextFormField(
    validator: (value) {
      if (value == null || value.isEmpty) {
        return 'Required';
      }
      return null;
    },
  ),
);

ElevatedButton(
  onPressed: () {
    if (_formKey.currentState.validate()) {
      print('Submitted');
    }
  },
  child: const Text('Submit'),
);
What is the error in this code?
medium
A. currentState can be null, should use currentState! to avoid error
B. validate() should be validate without parentheses
C. Validator function must return a boolean, not a string
D. TextFormField missing controller property

Solution

  1. Step 1: Check usage of currentState

    currentState can be null if the form is not mounted, so calling validate() without null check causes error.
  2. Step 2: Identify correct null safety usage

    Using _formKey.currentState!.validate() asserts non-null and avoids runtime error.
  3. Final Answer:

    currentState can be null, should use currentState! to avoid error -> Option A
  4. Quick Check:

    Use currentState! to safely call validate() [OK]
Hint: Use currentState! to avoid null errors on validate() [OK]
Common Mistakes:
  • Calling validate() without null check
  • Thinking validator returns boolean
  • Misusing validate as property
5. You want to submit a form and show a success message only if all fields are valid. Which Flutter code snippet correctly performs this action?
hard
A. if (_formKey.currentState.validate) { print('Success!'); }
B. if (_formKey.currentState!.validate()) { ScaffoldMessenger.of(context).showSnackBar( SnackBar(content: Text('Success!')) ); }
C. if (_formKey.validate()) { showDialog(context: context, builder: (_) => Text('Success!')); }
D. if (_formKey.currentState!.validate()) { Navigator.pushNamed(context, '/success'); }

Solution

  1. Step 1: Validate form state correctly

    Use _formKey.currentState!.validate() to check all fields are valid.
  2. Step 2: Show success feedback

    Use ScaffoldMessenger.of(context).showSnackBar() to display a success message to the user.
  3. Step 3: Check other options

    if (_formKey.currentState.validate) { print('Success!'); } misses parentheses and null safety, C uses invalid method, D navigates instead of showing message.
  4. Final Answer:

    if (_formKey.currentState!.validate()) { ScaffoldMessenger.of(context).showSnackBar( SnackBar(content: Text('Success!')) ); } -> Option B
  5. Quick Check:

    Validate then show SnackBar for success [OK]
Hint: Validate with currentState! then show SnackBar for feedback [OK]
Common Mistakes:
  • Calling validate without parentheses or null check
  • Using invalid methods on form key
  • Showing message without ScaffoldMessenger
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