Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Using an Isolate in Flutter
import 'dart:async';
import 'package:flutter/material.dart';
import 'dart:isolate';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Isolate Demo',
theme: new ThemeData(
primarySwatch: Colors.blue,
),
home: new MyHomePage(title: 'Flutter Isolates'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
Isolate _isolate;
bool _running = false;
static int _counter = 0;
String notification = "";
ReceivePort _receivePort;
void _start() async {
_running = true;
_receivePort = ReceivePort();
_isolate = await Isolate.spawn(_checkTimer, _receivePort.sendPort);
_receivePort.listen(_handleMessage, onDone:() {
print("done!");
});
}
static void _checkTimer(SendPort sendPort) async {
Timer.periodic(new Duration(seconds: 1), (Timer t) {
_counter++;
String msg = 'notification ' + _counter.toString();
print('SEND: ' + msg);
sendPort.send(msg);
});
}
void _handleMessage(dynamic data) {
print('RECEIVED: ' + data);
setState(() {
notification = data;
});
}
void _stop() {
if (_isolate != null) {
setState(() {
_running = false;
notification = '';
});
_receivePort.close();
_isolate.kill(priority: Isolate.immediate);
_isolate = null;
}
}
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text(widget.title),
),
body: new Center(
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Text(
notification,
),
],
),
),
floatingActionButton: new FloatingActionButton(
onPressed: _running ? _stop : _start,
tooltip: _running ? 'Timer stop' : 'Timer start',
child: _running ? new Icon(Icons.stop) : new Icon(Icons.play_arrow),
),
);
}
}
@lucasdanbatista

This comment has been minimized.

Copy link

@lucasdanbatista lucasdanbatista commented May 27, 2020

Hello! Thanks for sharing this! I was having difficulties to run a simple timer in background. Your sample code was useful! Based on it, I created this counter with the possibility to pass an initial time as parameter. I hope this can help other people too.

import 'dart:async';  
import 'dart:isolate';  
  
class CountdownTimer {  
  final receivePort = ReceivePort();  
  Isolate _isolate;  
  
 void stop() {  
    receivePort.close();  
  _isolate.kill(priority: Isolate.immediate);  
  }  
  
  Future<void> start(Duration initialDuration) async {  
    Map map = {  
      'port': receivePort.sendPort,  
  'initial_duration': initialDuration,  
  };  
  _isolate = await Isolate.spawn(_entryPoint, map);  
  receivePort.sendPort.send(initialDuration);  
  }  
  
  static void _entryPoint(Map map) async {  
    Duration initialTime = map['initial_duration'];  
  SendPort port = map['port'];  
  
  Timer.periodic(  
      Duration(seconds: 1),  
  (timer) {  
        if (timer.tick == initialTime.inSeconds) {  
          timer.cancel();  
  port.send(timer.tick);  
  port.send('Timer finished');  
  } else {  
          port.send(timer.tick);  
  }  
      },  
  );  
  }  
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.