FutureBuilder in Flutter is a convenient way that is used for asynchronous tasks. We can handle the user interface before completing the task as well as before and after. Have a look in this tutorial below.
How you to use FutureBuilder in Flutter
In this example we are going to call an api through function in a Futurebuilder.
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'FutureBuilder Example',
home: MyHomePage(),
);
}
}
class MyHomePage extends StatelessWidget {
// Simulated asynchronous data fetching function
Future<List<String>> fetchData() async {
// Simulate network request delay
await Future.delayed(Duration(seconds: 2));
// Simulated data
return ['Item 1', 'Item 2', 'Item 3'];
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('FutureBuilder Example'),
),
body: Center(
child: FutureBuilder<List<String>>(
future: fetchData(), // Call the asynchronous function
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return CircularProgressIndicator(); // Show a loading indicator while fetching data
} else if (snapshot.hasError) {
return Text('Error: ${snapshot.error}'); // Show an error message if data fetching fails
} else {
// Data fetching succeeded, build the UI with the fetched data
List<String> data = snapshot.data;
return ListView.builder(
itemCount: data.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(data[index]),
);
},
);
}
},
),
),
);
}
}
Explanation
We needed to wrap the widget for that we want to use the FutureBuilder like in the above example. We want to call an api and the response data will be shows, so in the FutureBuilder(), call that function. It has several states by using them you can manage the UI, those are:
fetchData(): Is a asynchronous function that returns a list of strings after a delay to mimic a network request.
ConnectionState.none: Means there are no connection then you can simply show some message.
ConnectionState.waiting: This state says that connection is made and its taking time to respond, you can show some loader icons inside it.
ConnectionState.done: You got the final result and use the result and show on the UI
You can see on the Flutter Pub as well as.
Suggestions
Flutter Isolate With Example | FlutterPoint
GridView in Flutter Full Example
Method Channel in Flutter Full Explanation With Examples
GetX State Management in Flutter
Top 20 Flutter Interview Questions
Card in Flutter With Full Examples
Thank you for reaching out FlutterTPoint. For any query of doubts you can comment in the comment section below.