If you need to call a background function after a duration even if the app is killed, an easy way is to push notification triggers.
1. Silent schedule Notifications
You can use silent push notification from flutter_local_notification with a tag
.
// Configuration
final FlutterLocalNotificationsPlugin localNotification = FlutterLocalNotificationsPlugin('app_icon');
const IOSNotificationDetails iosNotificationDetails =
IOSNotificationDetails(
categoryIdentifier: 'plainCategory',
);
const AndroidNotificationDetails androidPlatformChannelSpecifics =
AndroidNotificationDetails(
'background id', 'background channel name',
channelDescription: 'For background triggers',
importance: Importance.max,
priority: Priority.high,
tag: 'backgroud_functions'
);
const notificationDetails = NotificationDetails(
android:androidPlatformChannelSpecifics,
ios: iosNotificationDetails,
androidAllowWhileIdle: true,
uiLocalNotificationDateInterpretation:
UILocalNotificationDateInterpretation.absoluteTime
);
// Initize plugin before runApp
localNotification.initialize(
initializationSettings,
onSelectNotification: (String? payload) async {
// Push notification logic
},
backgroundHandler:(NotificationActionDetails details){
// filter background triggers from push notifications and execute.
if(details.payload.contains(isBackground)){
// run Any predefined function with parameters from payload
runFunctions(details.payload[arg1], details.payload[arg2],)
}
....
// your usual push notification logic
},
);
);
// Calling and setting schedule function
await localNotification.zonedSchedule(
function_id,
null, // not title we don't want to show a notification
null, // not body we don't want to show a notification
tz.TZDateTime.now(tz.local).add(duration_you_need), // set time here.
notificationDetails,
payload: {isBackground: true, argument1:'value', arg2: 'value'},
);
// to cancel
localNotification.cancel(function_id, tag: 'backgroud_functions');
- OR Use background fetch
Check the documentation for details.
timeout
? – Spermary