Sobes.tech
Middle

What is the execution model of applications in Flutter?

sobes.tech AI

Answer from AI

Flutter uses a single-threaded execution model for the user interface.

Main components of the execution model:

  • UI Thread (or Isolate): The main thread where all Dart code runs, widgets are built, gestures are processed, and rendering occurs.
  • Platform Channel: A mechanism for interacting between Dart code and native platform APIs (Android/iOS). Data exchange is asynchronous.
  • Event Loop: The event processing loop in the UI Thread. It handles:
    • User input.
    • Timers.
    • Results of asynchronous operations (e.g., network requests).
    • Rendering events.
  • Async/Await: Language constructs in Dart for non-blocking operations. They allow performing long tasks without freezing the UI Thread.
  • Isolates: Independent units of work that can execute Dart code in parallel with the UI Thread. Used for heavy computations to avoid blocking the UI. They do not share memory directly with the UI Thread; interaction occurs via messages (ports).

Example of using async/await for a non-blocking operation:

Future<String> fetchData() async {
  // Simulate a long operation, e.g., a network request
  await Future.delayed(Duration(seconds: 2));
  return 'Data received!';
}

void main() async {
  print('Starting execution...');
  String result = await fetchData(); // Wait for fetchData to complete
  print(result);
  print('Execution finished.');
}

Example of using Isolate for performing heavy tasks:

import 'dart:isolate';

// Function to be executed in a new Isolate
int heavyComputation(int value) {
  int result = 0;
  for (int i = 0; i < value; i++) {
    result += i;
  }
  return result;
}

void main() async {
  print('Main thread: Starting heavy computations...');

  // Create a port for message exchange
  ReceivePort receivePort = ReceivePort();

  // Spawn a new Isolate and pass it the function and send port
  await Isolate.spawn(heavyComputationWrapper, [1000000000, receivePort.sendPort]);

  // Wait for message from Isolate
  int result = await receivePort.first;

  print('Main thread: Result received - $result');
}

// Helper function to pass arguments to the function in Isolate
void heavyComputationWrapper(List<dynamic> args) {
  int value = args[0];
  SendPort sendPort = args[1];
  int result = heavyComputation(value);
  sendPort.send(result); // Send result back to main thread
}

The execution model in Flutter is designed to ensure smooth rendering at 60 FPS (or 120 FPS with support), avoiding UI freezes by performing most operations on the UI Thread and using asynchronous mechanisms and Isolates for heavy tasks.