Junior — Middle
Explain what the FutureBuilder widget is in the context of interface development in Flutter.
sobes.tech AI
Answer from AI
The FutureBuilder widget in Flutter is used to build an interface that depends on the result of an asynchronous operation (Future). It listens to the state of the Future and automatically rebuilds the UI when the state changes (for example, loading, successful data retrieval, or error).
Example of usage:
FutureBuilder<String>(
future: fetchData(), // asynchronous function returning Future<String>
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return CircularProgressIndicator(); // show loading indicator
} else if (snapshot.hasError) {
return Text('Error: \\${snapshot.error}');
} else if (snapshot.hasData) {
return Text('Data: \\${snapshot.data}');
} else {
return Text('No data');
}
},
)
Thus, FutureBuilder simplifies working with asynchronous data and updating the interface depending on the loading state.