Flutter Future then
In the world of modern app development, responsiveness and smooth user experiences are non-negotiable. Flutter, with its rich set of asynchronous features, provides developers with powerful tools to handle operations that take time, such as network requests or file I/O.
One of these tools is the Future class, and its then method plays a crucial role in managing the flow of asynchronous code. In this article, we’ll dive into how using Future and its then method can help you create more efficient, responsive, and robust Flutter applications.
By mastering these concepts, you’ll be equipped to handle asynchronous tasks with ease, ensuring that your apps perform seamlessly and meet users’ expectations.
Defining Asynchronous Functions:
- fetchData1(): This function simulates a delay of 3 seconds before returning “Data 1 received”.
- fetchData2(result): This function takes a result parameter, simulates a 2-second delay, and then appends ” – Data 2 received” to the result.
- process(result): This function takes a result parameter, simulates a 1-second delay, and appends ” – Data 3 received” to the result.
Chaining Operations with then:
- fetchData1().then(…): After fetchData1 completes, its result is passed to the next function.
- fetchData2(value).then(…): The result from fetchData1 is used in fetchData2, which then passes its result to process.
- process(value).then(…): Finally, process completes its operation, and the final result is printed to the console.
How It Works
- Sequential Execution: The then method is used to execute functions in sequence, where each function waits for the previous one to complete before starting.
- Handling Results: Each then method receives the result of the previous Future, allowing for a chain of dependent asynchronous operations.
- Error Handling: Although not shown in this example, you can also handle errors by adding .catchError(…) at the end of the chain.
main.dart :
Here’s a simple example to illustrate how you can chain asynchronous operations using Future and then in Flutter:
void main() async { // Step 1: Define asynchronous functions Future<String> fetchData1() async { await Future.delayed(const Duration(seconds: 3)); return "Data 1 received"; } Future<String> fetchData2(result) async { await Future.delayed(const Duration(seconds: 2)); return "$result - Data 2 received"; } Future<String> process(result) async { await Future.delayed(const Duration(seconds: 1)); return "$result - Data 3 received"; } // Step 2: Chain asynchronous operations using `then` fetchData1().then((value) => { fetchData2(value).then((value) => process(value).then((value) => print(value))) }); }
If you have any questions, feel free to drop them in the comments below. If you enjoyed this tutorial, show us some love by liking and sharing for more exciting updates