我想在 Flutter 中创建一个计步器应用程序,所以我使用了 Flutter 计步器插件,它运行良好,但我想每次都运行这个插件来计算用户步数,即使主应用程序已关闭。
我发现我可以使用 dart 隔离来创建一个任务,该任务可以在远离主线程的另一个线程中运行,并通过端口在它们之间进行通信。
String _stepCountValue = '0';
ReceivePort _receivePort;
Isolate isolate;
iniState() {
super.initState();
_start();
}
void _start() async {
_receivePort = ReceivePort();
isolate = await Isolate.spawn(initPlatformState,
_receivePort.sendPort);
_receivePort.listen((data) {
print(data);
setState(() {
_stepCountValue = "$data";
});
}, onDone: () {
print("done!");
});
}
static void initPlatformState(SendPort sendPort) async {
Pedometer pedometer = new Pedometer();
pedometer.stepCountStream.listen((int stepCountValue) {
print("------------------> $stepCountValue");
sendPort.send(stepCountValue);
}, onError: (error){print(error);}, onDone: (){}, cancelOnError:
true);
}
我希望输出是用户步骤数。
但我得到那个错误
I/flutter (26151): ══╡ EXCEPTION CAUGHT BY SERVICES LIBRARY ╞══════════════════════════════════════════════════════════
I/flutter (26151): The following _CompileTimeError was thrown while activating platform stream on channel
I/flutter (26151): pedometer.eventChannel:
I/flutter (26151): error: native function 'Window_sendPlatformMessage' (4 arguments) cannot be found
I/flutter (26151): When the exception was thrown, this was the stack:
I/flutter (26151): #0 Window.sendPlatformMessage (dart:ui/window.dart:868:9)
I/flutter (26151): #1 BinaryMessages._sendPlatformMessage (package:flutter/src/services/platform_messages.dart:46:15)
I/flutter (26151): #2 BinaryMessages.send (package:flutter/src/services/platform_messages.dart:97:12)
I/flutter (26151): #3 MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:295:50)
I/flutter (26151): <asynchronous suspension>
I/flutter (26151): #4 EventChannel.receiveBroadcastStream.<anonymous closure> (package:flutter/src/services/platform_channel.dart:490:29)
I/flutter (26151): <asynchronous suspension>
I/flutter (26151): #12 StepCounterState.initPlatformState (package:stepcounter/main.dart:59:30)
I/flutter (26151): <asynchronous suspension>
I/flutter (26151): #13 _startIsolate.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:303:17)
I/flutter (26151): #14 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:171:12)
I/flutter (26151): (elided 7 frames from package dart:async)