0

I'm trying to run an isolated function in Flutter. Here is my code:

This is the function I use to call the isolated function (runs inside the widget):

void start() async {
  ReceivePort receivePort =
      ReceivePort(); //port for this main isolate to receive messages.
  isolate = await Isolate.spawn(runTimer, receivePort.sendPort);
  receivePort.listen((data) {
    print('RECEIVE: ' + data + ', ');
  });
}

@override
void initState() {
  _loading = true;
  start(); //caled it here
  setState(() {});
  trackLocation();
  getNewOrders();
  getOrders();
  super.initState();
}

And here is the function I call (top-level function):

void runTimer(SendPort sendPort) {
  int counter = 0;
  Timer.periodic(new Duration(seconds: 1), (Timer t) {
    counter++;
    String msg = 'notification ' + counter.toString();
    print('SEND: ' + msg + ' - ');
    sendPort.send(msg);
  });
}

class NewOrdersList extends StatefulWidget {
//.....................................

I'm getting this error:

[ERROR:flutter/runtime/dart_isolate.cc(882)] Unable to resolve function 'runTimer' in library 'package:delivery_runner_driver/screens/new_order_list.dart'

NOTE

When I add the function inside the widget, it gives me this error:

Exception has occurred. ArgumentError (Invalid argument(s): Isolate.spawn expects to be passed a static or top-level function)

TylerP
  • 9,600
  • 4
  • 39
  • 43
Ahmed Wagdi
  • 3,913
  • 10
  • 50
  • 116

0 Answers0