DEV Community

Flutter Tanzania
Flutter Tanzania

Posted on

Building Asynchronous Flutter Applications with FutureBuilder

FutureBuilder is a powerful widget in Flutter that allows you to build your UI based on the state of a Future. A Future represents a value that is not available yet, but will be available at some point in the future.

When you use FutureBuilder, you pass a Future to it and a builder function. The builder function gets called whenever the state of the Future changes. The state of the Future can be one of three possibilities:

  • ConnectionState.active: The Future is currently running and has not yet completed.

  • ConnectionState.done: The Future has completed and either has a value or an error.

  • ConnectionState.none: The Future has not yet started.

Based on the state of the Future, you can build different widgets to show the user different UI elements. For example, if the Future is still running, you can show a loading spinner. If the Future has completed with a value, you can show the value. If the Future has completed with an error, you can show an error message.

Here is an example of how you can use FutureBuilder in your Flutter application:

class MyApp extends StatelessWidget {
  Future<String> _loadData() async {
    await Future.delayed(Duration(seconds: 3)); // simulate network delay
    return "Hello, World!";
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("FutureBuilder Example"),
      ),
      body: Center(
        child: FutureBuilder<String>(
          future: _loadData(),
          builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
            if (snapshot.connectionState == ConnectionState.waiting) {
              return CircularProgressIndicator();
            } else if (snapshot.hasError) {
              return Text("Error: ${snapshot.error}");
            } else {
              return Text("Data: ${snapshot.data}");
            }
          },
        ),
      ),
    );
  }
}

Enter fullscreen mode Exit fullscreen mode

In this example, _loadData() simulates a network request and returns a string after a delay of 3 seconds. FutureBuilder is used to build the UI based on the state of the Future returned by _loadData(). If the Future is still running, a CircularProgressIndicator is displayed. If the Future has completed with an error, an error message is displayed. Finally, if the Future has completed successfully, the data is displayed on the screen.

FutureBuilder is an essential widget in Flutter that can help you make your applications more responsive by allowing you to build your UI based on asynchronous operations. By using it correctly, you can provide a better user experience for your users.

Top comments (0)