0

The title says almost all - I'm not sure how to call invoke and on methods from the Flutter_background_service plugin, so that UI will be able to receive messages from the background and vice-versa? Any advice would be much appreciated.

May
  • 93
  • 7

1 Answers1

0

Since you don't really state your problem, it's hard to give much details.. but why don't you just look at the example of the plugin you've stated..

https://pub.dev/packages/flutter_background_service/example

on the UI just listen for the method you want the background thread to send using on method and subscribe to the stream. The above example uses that stream in a builder to update the UI:

            StreamBuilder<Map<String, dynamic>?>(
              stream: FlutterBackgroundService().on('update'),
              builder: (context, snapshot) {
                if (!snapshot.hasData) {
                  return const Center(
                    child: CircularProgressIndicator(),
                  );
                }

                final data = snapshot.data!;
                String? device = data["device"];
                DateTime? date = DateTime.tryParse(data["current_date"]);
                return Column(
                  children: [
                    Text(device ?? 'Unknown'),
                    Text(date.toString()),
                  ],
                );
              },
            ),

On the background thread you would just use the service instance you get from the plugin and call the invoke methods on that method name you are listening to in the frontend, and pass in data..

also from that example..

    service.invoke(
      'update',
      {
        "current_date": DateTime.now().toIso8601String(),
        "device": device,
      },
    );
Herbert Poul
  • 4,512
  • 2
  • 31
  • 48