Skip to content

Instantly share code, notes, and snippets.

@MarioCarlosChita
Forked from CodingWithTashi/main.dart
Created May 20, 2023 22:50
Show Gist options
  • Save MarioCarlosChita/4f57929d1970dea883aa405454e34ad5 to your computer and use it in GitHub Desktop.
Save MarioCarlosChita/4f57929d1970dea883aa405454e34ad5 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