-
-
Save MarioCarlosChita/4f57929d1970dea883aa405454e34ad5 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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