Flutter: Print to console from Dart isolates?

Issue

Having trouble finding information about this online. I’m just trying to figure out if a particular function in a Dart isolate is actually being run. The only way I know how to do this is by using the print() function, but either my function isn’t being run, or print()s from an isolate don’t show up in the console using flutter run. I don’t even know which is the case.

Here is the code that I’m trying to verify is being run, namely the onStart function:

void _entrypoint() => AudioServiceBackground.run(() => AudioPlayerTask());

class AudioPlayerTask extends BackgroundAudioTask {
  
  onStart(Map<String, dynamic> params) async {
    print('*** HELLO ***');
  }
}

This is the calling code, from the state of the Flutter app:

  initAudio() async {
    // Not sure if this is necessary, but according to some, it is.
    await AudioService.connect();

    // This should run the `onStart` function above.
    await AudioService.start(backgroundTaskEntrypoint: _entrypoint);

    print('*** THIS IS RUNNING ***');
  }

  @override
  void initState() {
    super.initState();

    initAudio();
  }

initAudio() is indeed being run, as proven by the print() statement within.

So the question is: Can I print() from a Dart isolate, and if not, how can I make an isolate somehow indicate that it is being run at all?

All of this is just to try and get the Flutter package audio_service working (version 0.16.2, specifically). I’ve been stuck at this point, just figuring out if the onStart is being run at all. As far as I can tell, it isn’t being run, but I don’t have a way to prove it.

(Bonus question: If it isn’t being run, I wonder why not. But that makes the question audio_service-specific, which probably merits a separate question. I am already using doing home: AudioServiceWidget(child:... and _entrypoint is top-level.)

Solution

I have gotten an isolate to work, and the answer is yes, the printed strings should be visible from within an isolate, at least in debug mode.

Answered By – Teekin

Answer Checked By – Robin (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *