Flutter Course: Adding a Loading Indicator in 15.10

Flutter is an open-source UI software development kit (SDK) developed by Google, supporting the creation of high-performance applications across various platforms, including mobile, web, and desktop apps. Flutter comes with many features that allow for rapid building and deployment of entire applications. In this tutorial, we will explain how to add a loading indicator to a Flutter application. Loading indicators are important elements that visually signal to users that a task is in progress, significantly enhancing the user experience.

1. What is a Loading Indicator?

A loading indicator is a UI element that signals to users that data is being loaded. It helps users understand the responsiveness of the app and alleviates concerns about potential delays. Flutter offers various loading indicators such as:

  • LinearProgressIndicator: Horizontal progress bar
  • CircularProgressIndicator: Circular progress bar
  • Custom loading indicators: Can be customized utilizing Flutter’s flexibility

2. Project Setup

To add a loading indicator, an existing Flutter project is required. To create a new Flutter project, run the following command to generate the basic project structure.

flutter create loading_indicator_example

Navigate to the created project directory and open the project using an IDE (e.g., Visual Studio Code).

cd loading_indicator_example

3. Adding a Loading Indicator

To add a loading indicator, we first need to define the user interface (UI). The following code is an example that uses CircularProgressIndicator and LinearProgressIndicator.


import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Loading Indicator Example',
      home: LoadingIndicatorDemo(),
    );
  }
}

class LoadingIndicatorDemo extends StatefulWidget {
  @override
  _LoadingIndicatorDemoState createState() => _LoadingIndicatorDemoState();
}

class _LoadingIndicatorDemoState extends State {
  bool _isLoading = false;

  void _fetchData() async {
    setState(() {
      _isLoading = true;
    });

    // Simulate a network request
    await Future.delayed(Duration(seconds: 3));

    setState(() {
      _isLoading = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Loading Indicator Example'),
      ),
      body: Center(
        child: _isLoading 
            ? CircularProgressIndicator() 
            : ElevatedButton(
                onPressed: _fetchData, 
                child: Text('Fetch Data'),
              ),
      ),
    );
  }
}

The above code uses CircularProgressIndicator to show the loading state to the user. When the button is clicked, the _fetchData function is called, which waits for 3 seconds before hiding the loading indicator.

4. Adding a LinearProgressIndicator

You can implement the same way to show the loading state using LinearProgressIndicator. To change the layout, simply modify the code.


import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Loading Indicator Example',
      home: LoadingIndicatorDemo(),
    );
  }
}

class LoadingIndicatorDemo extends StatefulWidget {
  @override
  _LoadingIndicatorDemoState createState() => _LoadingIndicatorDemoState();
}

class _LoadingIndicatorDemoState extends State {
  bool _isLoading = false;

  void _fetchData() async {
    setState(() {
      _isLoading = true;
    });

    await Future.delayed(Duration(seconds: 3));

    setState(() {
      _isLoading = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Loading Indicator Example'),
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          _isLoading 
                ? LinearProgressIndicator() 
                : ElevatedButton(
                    onPressed: _fetchData, 
                    child: Text('Fetch Data'),
                  ),
        ],
      )
    );
  }
}

5. Customizing Loading Indicators

You can customize the default loading indicators provided by Flutter to create a more unique and appealing UI. The following is an example of customization by adjusting color, size, and shape.


import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Customized Loading Indicator Example',
      home: LoadingIndicatorDemo(),
    );
  }
}

class LoadingIndicatorDemo extends StatefulWidget {
  @override
  _LoadingIndicatorDemoState createState() => _LoadingIndicatorDemoState();
}

class _LoadingIndicatorDemoState extends State {
  bool _isLoading = false;

  void _fetchData() async {
    setState(() {
      _isLoading = true;
    });

    await Future.delayed(Duration(seconds: 3));

    setState(() {
      _isLoading = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Customized Loading Indicator Example'),
      ),
      body: Center(
        child: _isLoading 
          ? CircularProgressIndicator(
              valueColor: AlwaysStoppedAnimation(Colors.green),
              strokeWidth: 10.0,
            ) 
          : ElevatedButton(
              onPressed: _fetchData, 
              child: Text('Fetch Data'),
            ),
      ),
    );
  }
}

6. Conclusion

Loading indicators are important elements that improve the user experience and maintain the identity of the application. With Flutter, you can easily add loading indicators and customize them as needed. We hope this tutorial helps you successfully add loading indicators to your Flutter applications.

7. Additional Resources

For more information about loading indicators, please refer to the official Flutter documentation or community forums. They contain various examples and tips that will be useful for troubleshooting.

Thank you!