How do you use the FutureBuilder widget in Flutter
How do you use the FutureBuilder widget in Flutter
In Flutter, the FutureBuilder widget is used to create widgets based on the latest snapshot of interaction with a Future. A Future represents the result of an asynchronous operation and can have two states: uncompleted or completed.
1. Introduction to Futures
A Future is an instance of the Future class in Dart. It represents the result of an asynchronous operation and can have two states: uncompleted or completed.
2. Using FutureBuilder
The FutureBuilder widget is used to create widgets based on the latest snapshot of interaction with a Future. It is Stateful in nature, i.e., it internally manages its own state, as we do in Stateful widgets.
3. Constructor of FutureBuilder
The FutureBuilder constructor takes four parameters:
- Key? key: The widget key is essential to addressing the relevant widget.
- Future? future: A Flutter future that can be accessed by the builder function.
- T? initialData: The starting point of the widget that will be used until the future has returned a value.
- required AsyncWidgetBuilder builder: The build strategy used by the builder.
4. AsyncSnapshot
The AsyncSnapshot holds some of the important data regarding the connection, data, error, etc. Some of its important fields are:
- connectionState: The ConnectionState enum can have 4 possible values: none, waiting, active, or done.
- hasData: Indicates whether the snapshot contains data.
- hasError: Indicates whether the snapshot contains an error.
- data: The data contained in the snapshot.
- error: The error contained in the snapshot.
5. Example of FutureBuilder
Here is an example of how to use the FutureBuilder widget:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'FutureBuilder Example',
home: FutureBuilderExample(),
);
}
}
class FutureBuilderExample extends StatefulWidget {
@override
_FutureBuilderExampleState createState() => _FutureBuilderExampleState();
}
class _FutureBuilderExampleState extends State<futurebuilderexample> {
Future<string> _future;
@override
void initState() {
super.initState();
_future = _getData();
}
Future<string> _getData() async {
await Future.delayed(Duration(seconds: 2));
return 'Data from Future';
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('FutureBuilder Example')),
body: FutureBuilder(
future: _future,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(child: CircularProgressIndicator());
} else if (snapshot.connectionState == ConnectionState.done) {
if (snapshot.hasData) {
return Center(child: Text(snapshot.data));
} else if (snapshot.hasError) {
return Center(child: Text('Error: ${snapshot.error}'));
}
}
return Container();
},
),
);
}
}
</string></string></futurebuilderexample>In this example:
- The FutureBuilder widget is used to create a widget based on the latest snapshot of interaction with a Future.
- The Future is created in the initState method and is used to fetch data after a delay of 2 seconds.
- The builder function is used to build the widget based on the snapshot.
- If the snapshot is in the waiting state, a CircularProgressIndicator is displayed.
- If the snapshot is in the done state and has data, the data is displayed.
- If the snapshot is in the done state and has an error, the error is displayed.
6. Conclusion
The FutureBuilder widget is a powerful tool in Flutter that allows you to create widgets based on the latest snapshot of interaction with a Future. By using the FutureBuilder widget, you can easily handle asynchronous operations and display the result in your app.