Future and FutureBuilder in Dart

CodeWithFlutter
2 Min Read

A Future is a way to represent a value that may not be available yet, or a computation that may not have completed. It is a way to perform asynchronous operations in Dart, which is the programming language used to develop Flutter applications.

You can get the actual value you want by using the await keyword in an async function, or by using the then method to register a callback that will be executed when the future completes.

Here’s an example:

Future<int> fetchData() async {
  return Future.delayed(Duration(seconds: 3), () => 42);
}

void main() async {
  int value = await fetchData();
  print(value); // prints 42
}

In Flutter, you can use a FutureBuilder widget to display the result of a future. The FutureBuilder takes a Future as an input and builds its contents based on the state of the future, such as loading, error, or the actual result.

Here’s an example:

Future<int> fetchData() async {
  return Future.delayed(Duration(seconds: 3), () => 42);
}

class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return FutureBuilder<int>(
      future: fetchData(),
      builder: (context, snapshot) {
        if (snapshot.hasData) {
          return Text('Result: ${snapshot.data}');
        } else if (snapshot.hasError) {
          return Text('Error: ${snapshot.error}');
        }
        return CircularProgressIndicator();
      },
    );
  }
}
Share this Article
Leave a comment