flutter_sound icon indicating copy to clipboard operation
flutter_sound copied to clipboard

[HELP] Error when execute FlutterSoundRecord in Isolate.spawn()

Open mahdidham opened this issue 4 years ago • 2 comments

After i test it to run record.OpenAudioSession() this error happened.

E/flutter: [ERROR:flutter/runtime/dart_isolate.cc(882)] Unhandled exception: ServicesBinding.defaultBinaryMessenger was accessed before the binding was initialized. If you're running an application and need to access the binary messenger before runApp() has been called (for example, during plugin initialization), then you need to explicitly call the WidgetsFlutterBinding.ensureInitialized() first. If you're running a test, you can call the TestWidgetsFlutterBinding.ensureInitialized() as the first line in your test's main() method to initialize the binding.

The error said that to implement WidgetsFlutterBinding.ensureInitialized() but I have already create it on the main(). I don't have any documentation to explain why this cannot run at flutter isolate. I am sure if there is some explanation

here's the code

void _isolateHandler() async {
    _receivePort = ReceivePort();
    _receivePort.listen(_handleMessage);
    print('isolate: start spawn');
    _isolate = await Isolate.spawn(_isolateRecord, _receivePort.sendPort);
  }

static void _isolateRecord(dynamic message) {
    SendPort sendPort;
    final receivePort = ReceivePort();
    print('isolate: thread isolate for record here');
    if (_recorder == null) {
      _recorder = FlutterSoundRecorder();
    }
    receivePort.listen((message) async {
      /*
        todo: receiving message from main thread.
         listen if main want to start record or stop record
       */
      if (message is Recordstate) {
        if (_recorder == null) {
          _recorder = FlutterSoundRecorder();
        }
        switch (message) {
          case Recordstate.record:
            // TODO: create new class for record or for audiorecorder worker
            await recording();
            break;
          case Recordstate.pause:
            // do pause record
            break;
          case Recordstate.stop:
            // do stop record
            await stopping();
            break;
        }
      }
    });

    if (message is SendPort) {
      print('get port from main thread');
      // TODO: resend send port to make sure isolate ready
      sendPort = message;
      sendPort.send(receivePort.sendPort);
      return;
    }
  }

mahdidham avatar Jan 12 '21 02:01 mahdidham

I cannot help you very much. I never used Isolates. Is your problem with Android or iOS ?

Android uses "Services". Perhaps the problem is somewhere here.

Larpoux avatar Jan 12 '21 08:01 Larpoux

This issue is stale because it has been open 90 days with no activity. Leave a comment or this will be closed in 7 days.

github-actions[bot] avatar Dec 19 '23 01:12 github-actions[bot]