0
0
Fluttermobile~5 mins

Loading and error states in Flutter

Choose your learning style9 modes available
Introduction

Loading and error states help users know what is happening in the app. They show when data is loading or if something went wrong.

When fetching data from the internet and waiting for a response.
When saving information and the app needs time to finish.
When a network error happens and the app cannot get data.
When a process takes time and the user should wait.
When showing a message if something fails.
Syntax
Flutter
if (isLoading) {
  return CircularProgressIndicator();
} else if (hasError) {
  return Text('Error loading data');
} else {
  return YourContentWidget();
}

Use a boolean like isLoading to show a spinner.

Use a boolean like hasError to show an error message.

Examples
Show a spinner while loading.
Flutter
if (isLoading) {
  return CircularProgressIndicator();
}
Show a simple error message if loading fails.
Flutter
if (hasError) {
  return Text('Failed to load data');
}
Show spinner while loading, then show data.
Flutter
if (isLoading) {
  return CircularProgressIndicator();
} else {
  return Text('Data loaded');
}
Sample App

This app shows a spinner for 3 seconds to simulate loading. Then it shows a success message. You can change hasError to true to see the error message instead.

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

void main() => runApp(const MyApp());

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  bool isLoading = true;
  bool hasError = false;

  @override
  void initState() {
    super.initState();
    // Simulate loading data
    Future.delayed(const Duration(seconds: 3), () {
      setState(() {
        isLoading = false;
        hasError = false; // Change to true to test error state
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: const Text('Loading and Error States')),
        body: Center(
          child: isLoading
              ? const CircularProgressIndicator()
              : hasError
                  ? const Text('Error loading data', style: TextStyle(color: Colors.red, fontSize: 18))
                  : const Text('Data loaded successfully!', style: TextStyle(fontSize: 18)),
        ),
      ),
    );
  }
}
OutputSuccess
Important Notes

Always give feedback to users so they know the app is working.

Use colors and icons to make error messages clear.

Keep loading states simple and easy to understand.

Summary

Loading states show a spinner or progress while waiting.

Error states show a message if something goes wrong.

Use simple booleans to control what the user sees.