Sobes.tech
Junior

What is FutureBuilder in Flutter?

sobes.tech AI

Answer from AI

Widget for building an interface based on asynchronous data received from Future.

Main parameters:

  • future: An instance of Future to observe.
  • initialData: Data displayed before the future completes.
  • builder: A function (AsyncWidgetBuilder) called on each change of the future state, receiving BuildContext and AsyncSnapshot.

States of AsyncSnapshot:

  • ConnectionState.none: The Future has not started yet.
  • ConnectionState.waiting: The Future is running.
  • ConnectionState.active: (Rare for Future) The Future has returned intermediate data.
  • ConnectionState.done: The Future has completed (successfully or with an error).

Example usage:

// Suppose we have a function that returns Future<String>
Future<String> fetchData() async {
  await Future.delayed(Duration(seconds: 2)); // Simulate network request
  return "Data loaded!";
}

// ... in the build method of a widget:
@override
Widget build(BuildContext context) {
  return FutureBuilder<String>(
    future: fetchData(), // Our Future
    builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
      if (snapshot.connectionState == ConnectionState.waiting) {
        // Show a loading indicator while the Future is running
        return CircularProgressIndicator();
      } else if (snapshot.hasError) {
        // Show an error message if the Future completed with an error
        return Text('Error: ${snapshot.error}');
      } else {
        // Show data if the Future completed successfully
        return Text('Result: ${snapshot.data}');
      }
    },
  );
}

Advantages:

  • Simplifies working with asynchronous operations in UI.
  • Automatically rebuilds UI when the Future state changes.
  • Clearly separates data loading logic from UI building logic.

Disadvantages:

  • May lead to unnecessary rebuilds if the Future is created inside the build method. It is recommended to create the Future once (e.g., in initState).
What is FutureBuilder in Flutter? — Flutter - sobes.tech