Why doesn't readLineSync works in an Isolate

Issue

void func(String dummy) {
  String? name = stdin.readLineSync();
  print(name);
  
}
void main(List<String> args) {
  Isolate.spawn(func, "Testing");

}

Why doesn’t my program prompts a user input ..and waits for me to enter it. Instead, it simply exits. Can someone help me out with an explanation. Not sure where to look.

I did find a similar question posted where they were using a while loop and using readLineSync inside that..and because of single thread of dart ..it wasn’t working there.

Solution

Dart programs terminates when the main-isolate does not have anymore to do, no events on the event queue, and does not subscribe to any event source which would result in new events being added to the event queue (like ReceivePort or Timer). It does not matter if spawned isolates are still being executed since they will just be killed.

You need to have the main-isolate to do something, or make the main-isolate subscribe to a signal from your spawned isolate using ReceivePort/SendPort as this will prevent the main-isolate from being terminated (since it subscribes to an event source which potentially could add new events on the event queue).

An example of using addOnExitListener on an Isolate object can be seen here:

import 'dart:async';
import 'dart:io';
import 'dart:isolate';

void func(String dummy) {
  print('Enter your name:');
  final name = stdin.readLineSync();
  print('Your name is: $name');
}

Future<void> main(List<String> args) async {
  final onExitReceivePort = ReceivePort();
  final isolate = await Isolate.spawn(func, "Testing");

  isolate.addOnExitListener(
    onExitReceivePort.sendPort,
    response: 'ReadLineIsolateStopped',
  );

  // Listen on spawned isolate is stopped event
  await for (final onExitEvent in onExitReceivePort) {
    print('Got event: $onExitEvent');
    onExitReceivePort.close();
  }
}

We are here closing the onExitReceivePort as soon we gets one event (since the spawned isolate is then gone) which will stop our main-isolate and the rest of the program.

Answered By – julemand101

Answer Checked By – Mildred Charles (FlutterFixes Admin)

Leave a Reply

Your email address will not be published.