Flutter Dart - isolate stops working when screen is off

Viewed 279

I have code to refresh data from server which I need to run even when screen is off. I tried to do this with an isolate:

static void isolateFunc(SendPort mainSendPort) async{
    String _answer = "";
    while(true){
      Socket socket = await Socket.connect(ipAddress, port, timeout: Duration(seconds: 5));
      socket.add(utf8.encode("connection test"));
      socket.listen((List<int> event) {
        _answer = utf8.decode(event);
      });
      socket.close();
      await Future.delayed(Duration(seconds: 5));
    }
}

This works fine when screen is on. But after switching off the screen it refreshs maybe for 5 times normally, then it refreshs for a few times each 30 sesconds(even when the delay is set to 5 seconds) and then it just stops. I am calling the isolate from initState like this:

 @override
  void initState() {
    super.initState();
    anotherRefresher();
    ReceivePort recievePort = ReceivePort();
    Isolate.spawn(isolateFunc, recievePort.sendPort);
  }

Battery optimalisation in android settings is off. I do not understand this :/ Any ideas how to deal with this please?

0 Answers
Related