C.Mahfoud
C.Mahfoud

Reputation: 90

How to run code in the background of a Flutter app?

I am working on a flutter app. I have a bunch of times of the day and I want to show an alert notification whenever a time comes and also change the UI of the app if it's running.

So I looked for what options I have, I found the followings

MY questions are:

  1. Which option is the best for my use case?
  2. Is it better implementing a time counter with delay by duration or using an alarm manager.
  3. How can I pass the data (the current time that comes) between the background task and my app so that I can update the UI?

PS: Currently We are interested in a solution that works at least for Android.

Upvotes: 1

Views: 5620

Answers (1)

Igor Kharakhordin
Igor Kharakhordin

Reputation: 9903

I don't think you need background tasks just to show notifications. Using flutter_local_notifications should be enough for your task. You can schedule a notification with this plugin for specific datetime. Inside of the app, you can use Timer to trigger at specific datetime. I'll show you a simple example:

demo

class _HomePageState extends State<HomePage> {
  FlutterLocalNotificationsPlugin notifPlugin;

  @override
  void initState() {
    super.initState();
    notifPlugin = FlutterLocalNotificationsPlugin();
  }

  Future<void> scheduleNotification(DateTime dateTime, String title) async {
    final now = DateTime.now();
    if (dateTime.isBefore(now)) {
      // dateTime is past
      return;
    }

    final difference = dateTime.difference(now);

    Timer(difference, () {
      showDialog(
        context: this.context,
        builder: (context) {
          return AlertDialog(
            content: Text(title),
          );
        }
      );
    });

    await notifPlugin.schedule(title.hashCode, title, title, dateTime, platformChannelSpecifics, payload: 'test');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: SafeArea(
        child: Container()
      ),
      floatingActionButton: Builder(
        builder: (context) {
          return FloatingActionButton(
            onPressed: () {
              final snackbar = SnackBar(content: Text('planned notification'), duration: Duration(seconds: 3));
              Scaffold.of(context).showSnackBar(snackbar);
              scheduleNotification(DateTime.now().add(Duration(seconds: 2)), 'Hello');
            },
          );
        }
      ),
    );
  }
}

But if you need to do some calculations or data fetch then background_fetch is what you need. The only problem with it Apple don't allow background tasks in most cases.

Upvotes: 3

Related Questions