One way of achieving this is using the flutter_app_badger package, which allows you to set the app badge using the updateBadgeCount
function. The trick is that you need to call this function at least once when your app is in the foreground before the app is put to the background or closed. One way to do this is to extend WidgetsBindingObserver
and override didChangeAppLifecycleState
in one of your widgets at the top of the widget tree:
class HomeScreen extends StatefulWidget {
@override
State<StatefulWidget> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> with WidgetsBindingObserver {
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
switch (state) {
case AppLifecycleState.resumed:
print("app in resumed");
if (PushNotificationsManager.appBadgeSupported) {
FlutterAppBadger.updateBadgeCount(14);
}
break;
case AppLifecycleState.inactive:
print("app in inactive");
break;
case AppLifecycleState.paused:
print("app in paused");
break;
case AppLifecycleState.detached:
print("app in detached");
break;
}
}
}
The app badge will not persist by itself, which is why you need to call this function at least once each time your app is in the foreground and a great place to do that is in didChangeAppLifecycleState
when AppLifecycleState
changes. If you call updateBadgeCount
in the AppLifecycleState.resumed
state like above, you'll also need to call updateBadgeCount
once when your app starts (you can do this in the init function of a class like PushNotificationsManager if you have one, otherwise just do it in one of your widgets init function).
You can also put updateBadgeCount
in the other states like AppLifecycleState.inactive
or AppLifecycleState.paused
, which will work in most cases but be cautious about this because if the app is closed/terminated without the inactive or paused state triggering, then the app badge will not be updated because the updateBadgeCount
function is not called.
For completeness: when your app is closed or in the background, you can update your app badge using Apple Push Notification service. Include the badge number in the payload, as shown here. Then when the user opens your app, the code above will execute and the badge number will be updated again so that when the user closes the app or the app goes into the background, the badge number will "persist" as seen by the user.
More about WidgetsBindingObserver and how to detect if app is in foreground/background here.