2

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)
4

0 に答える 0