isolates in flutter
Multithreading in Flutter using Dart isolates

Hi Guy’s Welcome to Proto Coders Point, You might be knowing about flutter isolate but did not understood why & how to to use it in flutter development.

What is Isolate in flutter

As you know that dart is a single threaded programming language, That means that dart can only perform single task at a time as In other langauges just like how we have thread, In dart language we have Isolates. Isolate in flutter is a seperate instance of Dart that will run concurrently with the main UI thread. With Isolate you can run a code parallel/seperately to ensure that the app runs smoothly & responsively when heavy & intensive operation is running at the background we use flutter isolates.

When to use flutter Isolates

You might be developing a flutter application & there might be a feature to be added in app that taks sometime to excute fully and may be heavy computation, communication netword operation, File I/o & all this you need to handle without blocking the user interface (UI) like causing laggy I+UI while the heavy task is running at backend with main thread.

About Flutter Isolate

In flutter dart, Isolate has it’s own memory heap where it perform the event loop, you can communicate between Isolate by using ‘sendPort’ , ‘receivePort’. In general I can say, Isolate are individual worker that can do the given task without affecting main UI thread & as you know that dart language is single threaded, By using Isolate in code you can acheive multiThreading in flutter application.

Video Tutorial

Why to use Isolate in flutter app

Before understanding why to use Isolate let’s check what happens when we perform heavy task & don’t use Isolates.

In Below code example without Isolate. In UI, I simply have a circularProgressIndicator() widget and a Button at the center of the screen.

When Button is press we call a function that will iterate a forLoop for almost 4 billion times which make the main thread busy, and thus as main thread is busy, Until this thread is free the UI component freezes & stuck until the loop completes.

code:

  int heavyLoad(int iteration){
    int value = 0;

    for(int i = 0;i<iteration;i++)
      value=i++;

    print(value);
    return value;

  }

Simply calling the above function when a button is pressed.

ElevatedButton(
                onPressed: (){
                  heavyLoad(4000000000);
                  },
  child: Text("Start Heavy Process without Isolate")),

Multithreading in Flutter using Dart isolates

Same thing let’s check what happens when we use Isolate to perform same task as above code does.

When button is been pressed let’s call a Isolate Function Instead of Normal function.

When you run flutter app note that the CircularProgressIndicator() which was getting freezed with now won’t affect & the UI will run smoothly as expected.

Code:

useIsolate() async{
  final ReceivePort receivePort = ReceivePort();

  try{
    await Isolate.spawn(runTask, [receivePort.sendPort,4000000000]);
  } on Object{
    print("Isolate Failed");
    receivePort.close();
  }
  final response = await receivePort.first;
  print('data Processed ${response}');
}

int runTask(List<dynamic> args){
  SendPort  resultPort = args[0];
  int value = 0;
  for(int i = 0;i<args[1];i++)
    value=i++;

  Isolate.exit(resultPort,value);
}

Calling a Isolate Function when button is pressed

ElevatedButton(
                onPressed: (){
                  useIsolate();
                },
                child: Text("Start Heavy Process with isolate")
)

ReceivePort allow isolate to listen for incoming message.

To create RecieverPort will use ‘ReceiverPort()’ constructor class.

Note: That each Isolate has it’s own ‘ReceiverPort’ can have multiple RecievedPot instance for handling different message.

SendPort is used to send message from one isolate to another, to send message to another isolate, we can use ‘send()’ method on SendPort instance with the message.

Conclusion

In conclusion, Flutter isolates are a powerful tool for running background tasks, achieving multitasking, and maintaining a responsive UI. By utilizing isolates effectively, developers can ensure optimal performance, responsiveness, and a seamless user experience in their Flutter applications.