Reputation: 90
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:
PS: Currently We are interested in a solution that works at least for Android.
Upvotes: 1
Views: 5620
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:
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