Flutter应用程序不会在应用程序启动时读取firebase通知数据,但会在后台状态下读取


当通知被点击时,我们使用下面的代码在应用程序中路由全局导航键。> main.dart' ' 'Void main() async {HttpOverrides。global = new MyHttpOverrides();WidgetsFlutterBinding.ensureInitialized ();等待Firebase.initializeApp ();FirebaseDynamicLink.init ();FirebaseNotification.init ();const MethodChannel("味道").invokeMethod("getFlavor")不要犹豫(字符串?味道){print('STARTED WITH FLAVOR $ FLAVOR ');if (flavor == 'PROD') {startPROD ();} else if (flavor == 'UAT') {startUAT ();}}) .catchError(错误){打印(错误);print('FAILED TO LOAD FLAVOR');}(;SystemChrome.setPreferredOrientations ([DeviceOrientation.portraitUp])不要犹豫((_){runApp (MyApp ());}(;}类MyApp扩展StatefulWidget {const MyApp({钥匙吗?Key}): super(Key: Key);@overrideState createState() => _MyAppState();}类_MyAppState扩展状态{@override小部件构建(BuildContext) {返回MaterialApp (debugShowCheckedModeBanner:假的,navigatorKey: AuthNav.navigationKey,onGenerateRoute:(路由设置){返回makeRoute (背景:背景下,routeName: settings.name !,参数:settings.arguments,);},);}}' ' '> firebase_notification.dart' ' 'FirebaseNotification.init () {initNotification = initNotification ();listenWhenMessageComes ();listenWhenAppInBackground ();listenWhenAppOpned ();listenWhenUserIsOnApp ();}未来的listenWhenAppOpned() async {//当用户点击通知时firebasemessage . onmessageopenedapp .listen((事件)async {如果事件。通知!= null) {//打印(event.notification ! .body);等待initNotification.onNotificationSelected (event.data.toString ());}}(;}' ' '数据路由控制代码> init_notification.dart' ' '未来onNotificationSelected(字符串?负载)async {//等待NotificationCount.removeCount();打印(载荷);if (payLoad != null) {列表str =有效载荷。replaceAll ("{", ").replaceAll ("}", "). 分割(",");映射结果= {};For (int I = 0;I = str[I].split(":");result.putIfAbsent (s [0] .trim (), () => s [1] .trim ());}打印("结果:结果美元");//等待goToRespectedPage(result);}}' ' '' ' 'goToRespectedPage(Map result) async {尝试{var routeName = NotificationRouteModel.fromJson(result).route;if (routeName.isNotEmpty) {if (userData != null) {switch (routeName) {案例/ViewPostPage":等待AuthNav.navigationKey.currentState ! .pushReplacementNamed (routeName参数:int.parse(结果[' kmdpWallId ']));打破;默认值:等待AuthNav.navigationKey.currentState ! .pushNamed("/主页");}} else {等待AuthNav.navigationKey.currentState ! .pushNamed ("/LoginPage ");}}} catch (err, stack) {打印(错);打印(栈);}}' ' '> routes.dart' ' 'makeRoute ({必需的BuildContext上下文;需要的字符串routeName,对象?参数}){最后PageRoute子=_buildRoute(context: context, routeName: routeName, arguments: arguments);返回的孩子;}_buildRoute ({required BuildContext context需要的字符串routeName,对象?参数,}) {switch (routeName) {案例‘/’:返回normalPageRoute (背景:背景下,页面:ChangeNotifierProvider (create: (context) => StartScreenProvider(),孩子:StartScreenPage (),),);案例/LoginPage":返回normalPageRoute (背景:背景下,页面:ChangeNotifierProvider (create: (context) => LoginPageProvider(),孩子:LoginPage (),),);案例/ViewPostPage":int kmdpWallId =参数作为int;返回normalPageRoute (背景:背景下,页面:ChangeNotifierProvider (create: (context) => ViewPostPageProvider(kmdpWallId: kmdpWallId),孩子:ViewPostPage (),),);//case '/addcommentpage '://PostData PostData = arguments作为PostData;//返回normalPageRoute(//context: context;//ChangeNotifierProvider(//create: (context) => AddCommentsProvider(postData: postData),//child: addcommentpage ());//case '/'://返回normalPageRoute(context: context, page: ChangeNotifierProvider(create: create))默认值:抛出'Route $routeName未定义';}}normalPageRoute ({required BuildContext context所需的Widget页面,}) => MaterialPageRoute ((BuildContext context) => page,maintainState:没错,fullscreenDialog:假);' ' '> auth_nav.dart' ' '静态最终GlobalKey navigationKey =GlobalKey ();' ' '
void main() async {
WidgetsFlutterBinding.ensureInitialized();
FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
await Firebase.initializeApp();
runApp(Home());
}
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) 
async {
await Firebase.initializeApp();
InAppNotifications().setStatus(true);
print("Handling a background message: ${message.messageId}");
PushNotificationService().navigateToPost(message.data);
}

"推送通知服务">

class PushNotificationService {
final FirebaseMessaging _fcm = FirebaseMessaging.instance;
final String urlString = dotenv.env["apiUrl"].toString();
final dataStorage = GetStorage();
Future initialise() async {
if (Platform.isIOS) {
_fcm.requestPermission();
}
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
print('Got a message whilst in the foreground!');
// print('Message data: ${message.data}');
Map data = message.data;
InAppNotifications().setStatus(true);
// print(screen);
});
FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
navigateToPost(message.data);
});
FirebaseMessaging.onBackgroundMessage((message) async {
navigateToPost(message.data);
return null;
});
}
final message = await 
FirebaseMessaging.instance.getInitialMessage();
if (message == null) {
return null;
} else {
return navigateToPost(message.data);
}
void navigateToPost(Map<String, dynamic> message) {
var screen = message["type"];
print(message);
}
}

相关内容

  • 没有找到相关文章

最新更新