Bird
Raised Fist0
Fluttermobile~20 mins

Error display patterns in Flutter - Mini App: Build & Ship

Choose your learning style10 modes available
Build: Error Display Screen
This screen shows how to display different types of error messages to users in a friendly way.
Target UI
┌───────────────────────────────┐
│ Error Display Screen           │
├───────────────────────────────┤
│ [Show Network Error]           │
│ [Show Validation Error]        │
│ [Show Unknown Error]           │
│                               │
│ Error message appears here    │
│                               │
└───────────────────────────────┘
Add three buttons labeled: 'Show Network Error', 'Show Validation Error', and 'Show Unknown Error'.
When a button is tapped, display a corresponding error message below the buttons.
Use red color for error messages and an icon to indicate error.
The error message area should be empty initially.
Make sure the UI is accessible with proper labels.
Starter Code
Flutter
import 'package:flutter/material.dart';

class ErrorDisplayScreen extends StatefulWidget {
  @override
  State<ErrorDisplayScreen> createState() => _ErrorDisplayScreenState();
}

class _ErrorDisplayScreenState extends State<ErrorDisplayScreen> {
  String _errorMessage = '';

  void _showError(String message) {
    setState(() {
      _errorMessage = message;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Error Display Screen')),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            ElevatedButton(
              onPressed: () {
                // TODO: Show network error message
              },
              child: const Text('Show Network Error'),
            ),
            ElevatedButton(
              onPressed: () {
                // TODO: Show validation error message
              },
              child: const Text('Show Validation Error'),
            ),
            ElevatedButton(
              onPressed: () {
                // TODO: Show unknown error message
              },
              child: const Text('Show Unknown Error'),
            ),
            const SizedBox(height: 24),
            // TODO: Display error message here
          ],
        ),
      ),
    );
  }
}
Task 1
Task 2
Task 3
Solution
Flutter
import 'package:flutter/material.dart';

class ErrorDisplayScreen extends StatefulWidget {
  @override
  State<ErrorDisplayScreen> createState() => _ErrorDisplayScreenState();
}

class _ErrorDisplayScreenState extends State<ErrorDisplayScreen> {
  String _errorMessage = '';

  void _showError(String message) {
    setState(() {
      _errorMessage = message;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Error Display Screen')),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            ElevatedButton(
              onPressed: () {
                _showError('Network error: Please check your internet connection.');
              },
              child: const Text('Show Network Error'),
            ),
            ElevatedButton(
              onPressed: () {
                _showError('Validation error: Please enter a valid email address.');
              },
              child: const Text('Show Validation Error'),
            ),
            ElevatedButton(
              onPressed: () {
                _showError('Unknown error occurred. Please try again later.');
              },
              child: const Text('Show Unknown Error'),
            ),
            const SizedBox(height: 24),
            if (_errorMessage.isNotEmpty)
              Row(
                children: [
                  const Icon(Icons.error_outline, color: Colors.red, semanticLabel: 'Error icon'),
                  const SizedBox(width: 8),
                  Expanded(
                    child: Text(
                      _errorMessage,
                      style: const TextStyle(color: Colors.red, fontSize: 16),
                      semanticsLabel: 'Error message',
                    ),
                  ),
                ],
              ),
          ],
        ),
      ),
    );
  }
}

We added three buttons that each show a different error message when tapped. The messages appear below the buttons in red color with an error icon to catch the user's attention. The error message area is empty at first and only shows when there is an error message to display. We used a Row with an Icon and Text for clear visual and accessibility. This pattern helps users understand what went wrong in a friendly and clear way.

Final Result
Completed Screen
┌───────────────────────────────┐
│ Error Display Screen           │
├───────────────────────────────┤
│ [Show Network Error]           │
│ [Show Validation Error]        │
│ [Show Unknown Error]           │
│                               │
│ ⚠ Network error: Please check  │
│   your internet connection.    │
│                               │
└───────────────────────────────┘
Tapping 'Show Network Error' displays a red error message with an error icon about internet connection.
Tapping 'Show Validation Error' displays a red error message about invalid email.
Tapping 'Show Unknown Error' displays a red error message about an unknown error.
If no button is tapped, no error message is shown.
Stretch Goal
Add a 'Clear Error' button that removes the error message when tapped.
💡 Hint
Add another ElevatedButton that calls _showError with an empty string to clear the message.

Practice

(1/5)
1. What is the best way to show an error message for a text input field in Flutter?
easy
A. Show a SnackBar without any text input changes
B. Use the errorText property in InputDecoration of TextField
C. Use a Container with red background below the field
D. Change the TextField font size to smaller

Solution

  1. Step 1: Understand Flutter form error display

    Flutter provides errorText in InputDecoration to show inline error messages below text fields.
  2. Step 2: Compare options for error display

    Using errorText is the standard and clear way. SnackBar is for brief messages, Container with red background is not standard, and font size change does not convey error.
  3. Final Answer:

    Use the errorText property in InputDecoration of TextField -> Option B
  4. Quick Check:

    Inline error message = errorText [OK]
Hint: Use errorText for inline field errors [OK]
Common Mistakes:
  • Using SnackBar for field errors
  • Changing font size to indicate error
  • Adding unrelated colored containers
2. Which Flutter widget is used to show a brief message at the bottom of the screen for errors?
easy
A. SnackBar
B. AlertDialog
C. Tooltip
D. Dialog

Solution

  1. Step 1: Identify widget for brief messages

    SnackBar is designed to show short messages at the bottom of the screen temporarily.
  2. Step 2: Differentiate from other widgets

    AlertDialog and Dialog are modal dialogs requiring user action. Tooltip shows hints on hover or long press, not error messages.
  3. Final Answer:

    SnackBar -> Option A
  4. Quick Check:

    Brief bottom message = SnackBar [OK]
Hint: SnackBar shows quick messages at screen bottom [OK]
Common Mistakes:
  • Confusing AlertDialog with SnackBar
  • Using Tooltip for error messages
  • Using Dialog without user action
3. What will happen if you run this Flutter code snippet?
ScaffoldMessenger.of(context).showSnackBar(
  SnackBar(content: Text('Error occurred!'))
);
medium
A. A red error dialog appears in the center
B. App crashes due to missing AlertDialog
C. A brief message 'Error occurred!' appears at the bottom
D. Nothing happens because SnackBar needs a Scaffold

Solution

  1. Step 1: Understand SnackBar usage with ScaffoldMessenger

    Using ScaffoldMessenger.of(context).showSnackBar() correctly shows a SnackBar message at the bottom of the screen.
  2. Step 2: Analyze the code behavior

    The SnackBar with text 'Error occurred!' will appear briefly at the bottom. It does not show a dialog or crash.
  3. Final Answer:

    A brief message 'Error occurred!' appears at the bottom -> Option C
  4. Quick Check:

    ScaffoldMessenger.showSnackBar = brief message at bottom [OK]
Hint: SnackBar shows text at bottom, not dialog [OK]
Common Mistakes:
  • Thinking SnackBar is a dialog
  • Assuming SnackBar needs AlertDialog
  • Believing SnackBar causes crash
4. You want to show an error alert dialog in Flutter but your code throws an exception. Which is the likely cause?
showDialog(
  context: context,
  builder: (context) => AlertDialog(
    title: Text('Error'),
    content: Text('Something went wrong'),
  ),
);
medium
A. Using showDialog without a valid context
B. Not wrapping AlertDialog in a MaterialApp
C. Missing Navigator.pop(context) to close dialog
D. AlertDialog requires a SnackBar inside

Solution

  1. Step 1: Check context usage in showDialog

    showDialog requires a valid BuildContext from a widget tree that includes a MaterialApp or WidgetsApp.
  2. Step 2: Identify common error cause

    Passing an invalid or null context causes exceptions. Missing Navigator.pop only affects closing, not showing. AlertDialog does not require SnackBar.
  3. Final Answer:

    Using showDialog without a valid context -> Option A
  4. Quick Check:

    Valid context needed for showDialog [OK]
Hint: Always pass valid context to showDialog [OK]
Common Mistakes:
  • Forgetting to provide valid context
  • Confusing SnackBar with AlertDialog requirements
  • Not handling dialog dismissal
5. You want to display multiple form field errors and a general error alert in Flutter. Which approach correctly combines inline errors and an alert dialog?
hard
A. Change field colors to red and show no dialogs
B. Show all errors only in a SnackBar at the bottom
C. Use AlertDialog for each field error and ignore inline errors
D. Use errorText for each field and show an AlertDialog for general errors

Solution

  1. Step 1: Understand error display roles

    Inline errors for fields use errorText to show specific issues. General errors affecting the whole form use AlertDialog to grab attention.
  2. Step 2: Evaluate options for combined error display

    Use errorText for each field and show an AlertDialog for general errors correctly uses inline errors for fields and an alert dialog for general errors. SnackBar is brief and not suitable for multiple detailed errors. Using AlertDialog for each field is disruptive. Changing colors alone is unclear.
  3. Final Answer:

    Use errorText for each field and show an AlertDialog for general errors -> Option D
  4. Quick Check:

    Inline errors + alert dialog [OK]
Hint: Combine errorText for fields and AlertDialog for general errors [OK]
Common Mistakes:
  • Showing all errors only in SnackBar
  • Using AlertDialog for each field error
  • Ignoring inline error messages
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