Flutter Parallel Network call

Issue

I am new in flutter. I need to call 5 API network calls in a single screen. It is taking very long time while i am using Async/await. How can we execute it on separate threads parallelly using isolate or anything else like it?

Solution

You may use isolate for this purpose isolate is a sort of multi threading in dart. Isolate creates a new thread and execute operation on the new thread so that the load will be distributed. You cannot send variables as a data back and forth but use port to send messages.

Here is a simple example of isolate with an API call and sending data back to the main thread using port.

First lets create a function which will be the entrypoint of isolate:

static entryPoint(SendPort sendPort)async{
    var response = await http.get('https://www.thecocktaildb.com/api/json/v1/1/search.php?s=margarita');
    sendPort.send(response.body); //sending data back to main thread's function
}

Now lets create isolate:

static void callApi()async{
    var recievePort = new ReceivePort(); //creating new port to listen data
    await Isolate.spawn(entryPoint, recievePort.sendPort);//spawing/creating new thread as isolates.
    recievePort.listen((message) {  //listening data from isolate
      print(message);
    });
}

Answered By – Abhay Kumar

Answer Checked By – Cary Denson (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *