I was trying to implement a stopwatch feature in a mobile app using Flutter, and I followed some other people's suggestion to use "isolate" to make the timer work in the background mode, and the timer works great when the app is open in the front, however, I found the timer stopped running whenever I put the app in the background mode, for example, when I clicked on the big button at the bottom of my iPhone 8 and open another app, and then later one I reopen the app, I found the timer was basically paused and only resumed the counting when I brought the app back to front...my sample code is as below.
import 'dart:isolate';
import 'dart:async';
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
Isolate? isolate;
ReceivePort? receivePort;
static int val = 0;
@override
void initState() {
super.initState();
spawnNewIsolate();
}
void spawnNewIsolate() async {
receivePort = ReceivePort();
try {
isolate = await Isolate.spawn(stopWatch, receivePort!.sendPort);
receivePort!.listen((dynamic message) {
setState(() {
print('New message from Isolate: $message');
val = int.parse(message);
});
});
} catch (e) {
print("Error: $e");
}
}
//spawn accepts only static methods or top-level functions
static void stopWatch(SendPort sendPort) {
Duration timerInterval = Duration(seconds: 1);
Timer? timer = Timer.periodic(timerInterval, (_) {
val++;
print('val:' + val.toString());
sendPort.send(val.toString());
});
}
@override
void dispose() {
super.dispose();
receivePort!.close();
isolate!.kill();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Isolate Demo"),
),
body: Center(
child:
Text('timer:' + val.toString()),
)
);
}
}
Datewhen you start and then determine elapsed time from that. - Paulw11