plus_plugins icon indicating copy to clipboard operation
plus_plugins copied to clipboard

[Question]: How To Get Context Inside Callback

Open TomerPacific opened this issue 4 years ago • 3 comments

What is your question?

When using the Flutter AlarmManagerPlus package and any one of its exposed methods, the callback we can pass is either of type Function or Function(int).

assert(callback is Function() || callback is Function(int));

Furthermore, we are instructed to mark our callback functions as static.

Due to all of these restrictions, I am wondering how I can access/get a context in one of the callbacks so that I can (for example) show an alert dialog when the callback is being triggered.

 static void _periodicTaskCallback() {
    // How to get context here?
  }

 void _schedulePeriodicAlarm() async {
    Duration duration = await _chooseDuration();
    await AndroidAlarmManager.periodic(duration, _periodicTaskId, _periodicTaskCallback);
  }

Just as a note, I have a basic one class stateful widget and I have tried accessing the state using a GlobalKey or using the OneContext package, but both don't appear to work.

You can see the code here.

Any guidance will be appreciated.

TomerPacific avatar Jul 15 '22 05:07 TomerPacific

As far as I know, you can not get BuildContext in the alarm's callback. AndroidAlarmManagerPlus plugin offers the background process even if the app is not running. Basically, your app is running the main isolate, and the alarm callback is executed in a different isolate. Flutter isolates do not share a memory, so you can not do anything with memory-resident objects.

The workaround is to run a local server in the main isolate and send a message from the callback. You can use any server including HTTP, WebSocket, and even firebase's cloud firestore.

Here's the fixed example from your code.

class _MyHomePageState extends State<MyHomePage> {
  // the rest of your code is intact. 
  HttpServer? server;

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

  setup() async {
    server ??= await HttpServer.bind('127.0.0.1', 4040);
    server!.listen((HttpRequest req) async {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('alarmed'),
        ),
      );
    });
  }

  @override
  void dispose() {
    server?.close();
    server = null;
    super.dispose();
  }

  @pragma("vm:entry-point")
  static _oneShotTaskCallback() async {
    final client = HttpClient();
    final req = await client.get('127.0.0.1', 4040, '/');
    await req.close();
  }
  // the rest of your code is intact. 
}

Or when you call _schedule{OneShot/Periodic}Alarm() method, launch the periodic callback future which checks the local database or files. And when the alarm ticks, change the value of the local database in the callback.

If you need an alarm that is only valid while the app is running, you can simply use Future.delayed, Timer, and Timer.periodic. In this case, you can use BuildContext as usual.

p.s. I am happy to find this issue with the interest of #hacktoberfest :)

wurikiji avatar Oct 21 '22 08:10 wurikiji

In addition, if what you want to do is to show a graphical alert when the alarm is on, then consider https://pub.dev/packages/flutter_local_notifications package.

wurikiji avatar Oct 21 '22 08:10 wurikiji

This issue is stale because it has been open 60 days with no activity. Remove stale label or comment or this will be closed in 15 days

github-actions[bot] avatar Jan 20 '23 00:01 github-actions[bot]