Skip to content

Instantly share code, notes, and snippets.

@CodingWithTashi
Created September 2, 2021 14:49
Show Gist options
  • Save CodingWithTashi/bab1231dec118cdbffb73a66f40af165 to your computer and use it in GitHub Desktop.
Save CodingWithTashi/bab1231dec118cdbffb73a66f40af165 to your computer and use it in GitHub Desktop.
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);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment