More
How to Optimize Async Operations in Flutter with Future.wait and Back4app
7 min
introduction asynchronous programming is essential in modern app development, especially when dealing with tasks like fetching data from multiple sources or performing multiple network requests however, handling multiple async calls efficiently can be challenging in flutter, the future wait method provides a powerful way to manage multiple futures , allowing your app to await several async operations concurrently and efficiently in this tutorial, you’ll learn how to use future wait in flutter to optimize the performance of your app when dealing with multiple async tasks we’ll integrate this technique with back4app, where you can perform concurrent data fetches from your backend, store the results, and significantly reduce the wait time for your users prerequisites to complete this tutorial, you will need a back4app account sign up for a free account at back4app com https //www back4app com flutter development environment set up on your local machine follow the flutter installation guide https //flutter dev/docs/get started/install if you haven't set it up yet basic knowledge of asynchronous programming in flutter and how to use back4app as a backend service if you're new to back4app, check out the getting started with back4app guide https //www back4app com/docs/get started/welcome step 1 – setting up your back4app backend create a back4app project log in to your back4app account https //dashboard back4app com/ and create a new project create parse classes in your back4app project, create two new parse classes named task and project the task class should have fields name (string) and completed (boolean) the project class should have fields title (string) and description (string) add sample data populate these classes with sample data that we will fetch concurrently using future wait in our flutter app get your back4app credentials navigate to your project settings to retrieve your application id and client key, which you’ll need to connect your flutter app to back4app step 2 – setting up your flutter project create a new flutter project open your terminal or command prompt and run add dependencies open pubspec yaml and add the following dependencies initialize parse in your app in lib/main dart , import the parse sdk and initialize it in the main function const keyapplicationid = 'your back4app app id'; const keyclientkey = 'your back4app client key'; const keyparseserverurl = 'https //parseapi back4app com'; await parse() initialize(keyapplicationid, keyparseserverurl, clientkey keyclientkey, autosendsessionid true); runapp(myapp()); replace 'your back4app app id' and 'your back4app client key' with your actual back4app credentials step 3 – fetching data concurrently with future wait create the taskprojectscreen widget in lib/main dart , add a new widget that will fetch data from both the task and project classes concurrently class taskprojectscreen extends statefulwidget { @override taskprojectscreenstate createstate() => taskprojectscreenstate(); } class taskprojectscreenstate extends state\<taskprojectscreen> { list\<parseobject>? tasks; list\<parseobject>? projects; string? errormessage; @override void initstate() { super initstate(); fetchdata(); } future\<void> fetchdata() async { try { // fetch tasks and projects concurrently final futures = \[ gettasks(), getprojects(), ]; final results = await future wait(futures); setstate(() { tasks = results\[0] as list\<parseobject>; projects = results\[1] as list\<parseobject>; }); } catch (e) { setstate(() { errormessage = e tostring(); }); } } future\<list\<parseobject>> gettasks() async { final query = querybuilder\<parseobject>(parseobject('task')); final response = await query query(); if (response success && response results != null) { return response results as list\<parseobject>; } else { throw exception('failed to load tasks'); } } future\<list\<parseobject>> getprojects() async { final query = querybuilder\<parseobject>(parseobject('project')); final response = await query query(); if (response success && response results != null) { return response results as list\<parseobject>; } else { throw exception('failed to load projects'); } } @override widget build(buildcontext context) { if (errormessage != null) { return center(child text('error $errormessage')); } if (tasks == null || projects == null) { return center(child circularprogressindicator()); } return listview( children \[ listtile(title text('tasks')), tasks! map((task) => listtile( title text(task get\<string>('name') ?? 'no name'), subtitle text('completed ${task get\<bool>('completed') ? 'yes' 'no'}'), )), listtile(title text('projects')), projects! map((project) => listtile( title text(project get\<string>('title') ?? 'no title'), subtitle text(project get\<string>('description') ?? 'no description'), )), ], ); } } this widget fetches tasks and projects concurrently using future wait , reducing the total wait time by handling both requests simultaneously step 4 – testing and running your app run your app using flutter run you should see a list of tasks and projects displayed on the screen both datasets are fetched concurrently, making the data retrieval process faster and more efficient conclusion in this tutorial, you learned how to use future wait to optimize asynchronous operations in your flutter app by fetching data from multiple sources concurrently and integrating with back4app, you made your app more responsive and reduced the overall wait time for your users using future wait in combination with a robust backend like back4app allows you to efficiently manage multiple asynchronous tasks and improve the performance of your flutter applications for more details on using back4app with flutter, check out the back4app flutter documentation https //www back4app com/docs/flutter/overview happy coding!