How to Run Tasks Without Freezing the UI

Example of Freezing the UI in Flutter

int complexTask() {
  int total = 0;
  for (int i = 0; i < 1000000000; i++) {
    total += i;
  }
  return total;
}

// Simple Flutter app setup with a button to trigger a heavy task
ElevatedButton(
  onPressed: () {
    int result = complexTask();
    print(result);
  },
  child: Text('Start Task'),
),


Step-by-Step Implementation of Isolates

For an isolate to work, the task it performs must be written outside any class. This ensures the task can run independently of the main UI thread:

int complexTask(int message) {
  int total = 0;
  for (int i = 0; i < 1000000000; i++) {
    total += i;
  }
  return total;
}


Spawning an Isolate

void runComplexTaskInIsolate() async {
  ReceivePort receivePort = ReceivePort();
  await Isolate.spawn(complexTaskIsolate, receivePort.sendPort);

  receivePort.listen((result) {
    print('Result: $result');
  });
}

void complexTaskIsolate(SendPort sendPort) {
  int result = complexTask(0);
  sendPort.send(result);
}