DEV Community

Moyeen Haider
Moyeen Haider

Posted on

Isolate Bliss: Elevate Your Flutter Experience✨

Imagine you’re the manager🧑‍💼 of a restauran🍽️t (your Flutter app). Your orders are increasing🚀, and your star chef👨‍🍳 (the Main Thread, which builds the UI) is busy with creating the perfect signature dish🍲 (rendering UI). A big group 🤼🧑‍🤝‍🧑arrives, demanding a complex, time-consuming feast (intensive business logic). You’re worried about delays and frustrated customers😓!

But then you remember Isolate😀, your secret kitchen in the bac😮‍💨k. It has its own independent chef🧑‍🍳 who can cook without interrupting the main kitchen’s flow. You send the group’s order to Isolate, where the chef🧑‍🍳 works actively while your star chef👨‍🍳 continues serving other guests. When the feast is ready🥗, Isolate sends it back carefully, and your restaurant works smoothly, everyone happy and well-fed!😊😋

Don’t Try to Understand it First. Just Go-Through the code, and re-read it, once when you finish the article.

import 'dart:async';
import 'dart:isolate';

// Main entry point for the restaurant app
void main() {
  runApp(MyRestaurantApp());
}

// Restaurant app widget
class MyRestaurantApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: RestaurantHomePage(),
    );
  }
}

// Home page for the restaurant app
class RestaurantHomePage extends StatefulWidget {
  @override
  _RestaurantHomePageState createState() => _RestaurantHomePageState();
}

// State for the home page
class _RestaurantHomePageState extends State<RestaurantHomePage> {
  double _progressValue = 0.0;
  String _result = "";

  /**
   * Simulates cooking a complex feast.
   */
  void prepareFeast() {
    for (int i = 0; i < 1000000000; i++) {
      // Simulating chopping, stirring, seasoning...
    }
  }

  /**
   * Updates the progress bar value.
   */
  void updateProgress(double value) {
    setState(() {
      _progressValue = value;
    });
  }

  /**
   * Updates the result text.
   */
  void updateResult(String result) {
    setState(() {
      _result = result;
    });
  }

  /**
   * Runs the feast preparation on the main thread.
   */
  void runIntenseBusinessLogicOnMainThread() {
    // Clear previous result
    updateResult("");

    // Start progress bar
    updateProgress(0.5);

    // Prepare feast on the main thread
    prepareFeast();

    // Update progress bar to completion
    updateProgress(1.0);

    // Update result
    updateResult("Feast prepared on the main thread!");
  }

  /**
   * Runs the feast preparation using an isolate.
   */
  void runIntenseBusinessLogicWithIsolate() async {
    // Clear previous result
    updateResult("");

    // Start progress bar
    updateProgress(0.5);

    // Create a kitchen hotline to communicate with the secret kitchen
    ReceivePort kitchenHotline = ReceivePort();

    // Send the order to the secret kitchen
    Isolate.spawn(prepareFeastInSecretKitchen, kitchenHotline.sendPort);

    // Listen for updates from the secret kitchen
    kitchenHotline.listen((message) {
      if (message is double) {
        // Update progress bar
        updateProgress(message);
      } else if (message == "done") {
        // Feast is ready!
        updateProgress(1.0);
        updateResult("Feast prepared in the secret kitchen!");
      }
    });

    // Send a "Start cooking!" message to the secret kitchen
    kitchenHotline.send("start");
  }

  /**
   * Secret kitchen chef's recipe for preparing the feast.
   */
  void prepareFeastInSecretKitchen(SendPort sendPort) {
    ReceivePort kitchenHotline = ReceivePort();
    sendPort.send(kitchenHotline.sendPort);

    kitchenHotline.listen((message) {
      if (message == "start") {
        prepareFeast(); // Start cooking the feast
        sendPort.send("done"); // Signal completion
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Restaurant Isolate Magic"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            CircularProgressIndicator(
              value: _progressValue,
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: runIntenseBusinessLogicOnMainThread,
              child: Text("Run on Main Thread"),
            ),
            ElevatedButton(
              onPressed: runIntenseBusinessLogicWithIsolate,
              child: Text("Run with Secret Kitchen"),
            ),
            SizedBox(height: 20),
            Text(_result),
          ],
        ),
      ),
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

Now, Let’s Understand What is Isolates?.
Isolates in Flutter are independent threads of execution, allowing tasks to run concurrently without interfering with the main thread. Unlike the main thread that handles UI, Isolates operate independently, opening a gateway to efficient parallelism.

Why Do We Need Isolates?
Let’s assume you’re a master chef🧑‍🍳 in a restaurant🍽️, flawlessly creating pizzas🍕 and plating excellent dishes (the smooth UI). Suddenly, a VIP💵 orders a complex, multi-course feast (a resource-intensive task). If you tackled this in the main kitchen, everything would grind to a halt — impatient diners, burnt offerings, and chaos!😮🤯😵‍💫

This is where the magic of isolates come in😉. They’re like your own secret kitchen, hidden from public view, where skilled sous chefs🧑‍🍳 (independent threads) can tirelessly work on the feast🥗 without disrupting the main kitchen’s rhythm. You can still create delicious food and keep your guests happy😊, while your hidden assistants precisely prepare the masterpiece✨.

Isolates act as guardians💂, shielding the main thread (your public kitchen) from the strain of heavy tasks. They take the pressure off😮‍💨, ensuring your restaurant (your app) runs like a well-oiled machine, leaving diners (users) with a sense of wonder and a truly delightful experience. So, embrace the secret cooks of Flutter — they’re the key to keeping your delicious (digital) creations flowing flawlessly, even when faced with the most demanding orders!😊😋

We need isolates in Flutter to ensure a responsive and smooth user interface. Isolates provide a way to execute resource-intensive tasks independently, preventing them from blocking the main thread. This separation allows the UI to remain responsive, ensuring a seamless user experience even during complex computations or time-consuming operations.

Top comments (0)