Hi Guy’s, Welcome to Proto Coders Point. In the changing world of mobile App development, App Performance plays an crucial role that can build you app business or break the plan if performance is weak. As a flutter developer where we build mobile application for cross platform like mobile, android, ios or desktop, where we need to focus of app performance in multiple operations simultaneously, can be making a API call to fetch data, executing database transaction or carrying out complex computations.
Sequential Execution of program
The most common mistake many application developer does is exciting an operation in a sequence, may be he is using async, He make mistake by executing operation one after another, which will lead into slowing down the app or user might see lag in UI while an operation is fetching data and will be poor user experience.
The Solution is concurrent execution of operations
Future.wait()
is a game-changer, when it comes handling multiple asynchronous operations concurrently. By using Future.wait()
we can execute multiple futures at the same time, Therefore this will reduce the over all waiting time and will lead to improving app performance.
Code Example – without using Future.wait()
Below code is by executing operation sequentially one by one.
The below code will take 4 seconds to completely run the program
void main() async{ var data1 = await delayedNumber(); print(data1); // Here there is a await of 2 second var data2 = await delayedString(); // Here there is a await of 2 second print(data2); // totally it take 4 seconds to completely run the program } Future<int> delayedNumber() async{ await Future.delayed(Duration(seconds:2)); return 1; } Future<String> delayedString() async{ await Future.delayed(Duration(seconds:2)); return 'Results'; }
Code Example – using Future.wait()
void main() async{ var data = await Future.wait([ delayedNumber(), delayedString() ]); print(data[0]); // [2,results] } Future<int> delayedNumber() async{ await Future.delayed(Duration(seconds:2)); return 1; } Future<String> delayedString() async{ await Future.delayed(Duration(seconds:2)); return 'Results'; }
Here by using By executing multiple futures concurrently, Future.wait()
reduces the overall waiting time for operations. This is particularly useful for tasks that are independent of each other, such as fetching data from different APIs or performing unrelated computations.