Displaying async values in Flutter
The build method in Flutter widgets is synchronous. That means it doesn’t like to wait for anything. But sometimes, we need to wait for a value to arrive in order to display it. Let’s think of a simple weather app that displays only the temperature of a city. The app needs to make a request to the backend, get the temperature value, and finally display it. It will have to wait for a response from the backend, but as we discussed, the build method does not like to wait for anything. So how do we solve this issue? Enter: FutureBuilder . FutureBuilder takes a value of type Future and displays widgets until it is resolved. In fact, we can specify which widgets to display not only while loading but also when an error occurs. Let’s see how we can use FutureBuilder in a simple app. First, create an app in a directory of your choice: flutter create future_builder --platforms = macos You can choose whichever platform you want. Open the project in your preferred IDE, and navigate to lib/main.dart . Replace the entire content of the file with the following: import 'package:flutter/material.dart' ; void main () { runApp ( const MyApp ()); } class MyApp extends StatelessWidget { const MyApp ({ super . key }); @override Widget build ( BuildContext context ) { return MaterialApp ( home: const MyHomePage ()); } } class MyHomePage extends StatelessWidget { const MyHomePage ({ super . key }); Future < int > _getTemperature () async { await Future . delayed ( Duration ( seconds: 3 )); // Dummy delay of three seconds. return 25 ; } Future < int > _getTemperatureError () async { await Future . delayed ( Duration ( seconds: 3 )); throw Exception ( 'An error occurred while retrieving the temperature value.' ); } Future < int ? > _getTemperatureEmpty () async { await Future . delayed ( Duration ( seconds: 3 )); return null ; } @override Widget build ( BuildContext context ) { return Scaffold ( body: Center ( child: FutureBuilder ( future: _getTemperature (), builder: ( context , snapshot )