![](/img/trans.png)
[英]Flutter: The notification badge counter on the iOS app icon on the home screen is not showing up (using FCM)
[英]How to have persistent badge icon on iOS using Flutter
即使在打开和关闭应用程序后,是否可以使用 flutter 将通知徽章保留在应用程序图标上? 例如:用户的徽章值为 6,打开应用程序阅读一条消息,关闭应用程序,徽章现在显示为 5。
我如何实现此功能? (专门寻找 iOS 解决方案,但如果您有提示,也有兴趣了解 Android 方面)
实现此目的的一种方法是使用flutter_app_badger包,它允许您使用updateBadgeCount
函数设置应用徽章。 诀窍在于,当您的应用程序处于前台时,您需要至少调用一次此函数,然后才能将应用程序置于后台或关闭。 一种方法是扩展WidgetsBindingObserver
并在小部件树顶部的一个小部件中覆盖didChangeAppLifecycleState
:
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;
}
}
}
应用程序徽章不会自行保留,这就是为什么每次您的应用程序在前台时您都需要至少调用一次此函数,并且当AppLifecycleState
更改时,在didChangeAppLifecycleState
中执行此操作的好地方。 如果您像上面那样在AppLifecycleState.resumed
状态下调用updateBadgeCount
,您还需要在应用程序启动时调用一次updateBadgeCount
(如果您有 PushNotificationsManager 类,您可以在类的 init 函数中执行此操作,否则只需在您的小部件初始化函数之一)。
您还可以将updateBadgeCount
置于其他状态,如AppLifecycleState.inactive
或AppLifecycleState.paused
,这在大多数情况下都有效,但对此要谨慎,因为如果应用程序在没有触发非活动或暂停状态的情况下关闭/终止,则应用程序徽章将未更新,因为未调用updateBadgeCount
函数。
为了完整起见:当您的应用程序关闭或在后台运行时,您可以使用 Apple 推送通知服务更新您的应用程序徽章。 在有效负载中包含徽章编号,如此处所示。 然后,当用户打开您的应用程序时,上面的代码将执行,徽章编号将再次更新,这样当用户关闭应用程序或应用程序进入后台时,徽章编号将“保持”为用户所见。
有关WidgetsBindingObserver以及如何检测应用程序是否处于前台/后台的更多信息,请点击此处。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.