Flutter Isolates Spawn using ReceivePort()

PHOTO EMBED

Tue Nov 08 2022 10:52:17 GMT+0000 (Coordinated Universal Time)

Saved by @yashmakan #flutter #dart

import 'dart:isolate';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: BodyWidget(),
      ),
    );
  }
}

class BodyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          CircularProgressIndicator(),
          ElevatedButton(
            child: Text('start'),
            onPressed: () async {

              //ReceivePort is to listen for the isolate to finish job
              final receivePort = ReceivePort();
              // here we are passing method name and sendPort instance from ReceivePort as listener
              await Isolate.spawn(
                  computationallyExpensiveTask, receivePort.sendPort);

              //It will listen for isolate function to finish
              receivePort.listen((sum) {
                print(sum);
              });
            },
          )
        ],
      ),
    );
  }
}

// this function should be either top level(outside class) or static method
void computationallyExpensiveTask(SendPort sendPort) {
  print('heavy work started');
  var sum = 0;
  for (var i = 0; i <= 1000000000; i++) {
    sum += i;
  }
  print('heavy work finished');
  //Remember there is no return, we are sending sum to listener defined defore.
  sendPort.send(sum);
}
content_copyCOPY

https://codingwithtashi.medium.com/isoltate-flutter-dart-multithreading-cf5f67de9b46