We used below code for routing through global navigation key in app when a notification is clicked. >main.dart ``` void main() async { HttpOverrides.global = new MyHttpOverrides(); WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp(); FirebaseDynamicLink.init(); FirebaseNotification.init(); const MethodChannel('flavor') .invokeMethod('getFlavor') .then((String? flavor) { print('STARTED WITH FLAVOR $flavor'); if (flavor == 'PROD') { startPROD(); } else if (flavor == 'UAT') { startUAT(); } }).catchError((error) { print(error); print('FAILED TO LOAD FLAVOR'); }); SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]) .then((_) { runApp(MyApp()); }); } class MyApp extends StatefulWidget { const MyApp({Key? key}) : super(key: key); @override State createState() => _MyAppState(); } class _MyAppState extends State { @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, navigatorKey: AuthNav.navigationKey, onGenerateRoute: (RouteSettings settings) { return makeRoute( context: context, routeName: settings.name!, arguments: settings.arguments, ); }, ); } } ``` >firebase_notification.dart ``` FirebaseNotification.init() { initNotification = InitNotification(); listenWhenMessageComes(); listenWhenAppInBackground(); listenWhenAppOpned(); listenWhenUserIsOnApp(); } Future listenWhenAppOpned() async { //When user clickes on notification FirebaseMessaging.onMessageOpenedApp.listen((event) async { if (event.notification != null) { // print(event.notification!.body); await initNotification.onNotificationSelected(event.data.toString()); } }); } ``` `code for routing control by data` >init_notification.dart ``` Future onNotificationSelected(String? payLoad) async { // await NotificationCount.removeCount(); print(payLoad); if (payLoad != null) { List str = payLoad.replaceAll("{", "").replaceAll("}", "").split(","); Map result = {}; for (int i = 0; i s = str[i].split(":"); result.putIfAbsent(s[0].trim(), () => s[1].trim()); } print("result:$result"); // await goToRespectedPage(result); } } ``` ``` Future goToRespectedPage(Map result) async { try { var routeName = NotificationRouteModel.fromJson(result).route; if (routeName.isNotEmpty) { if (userData != null) { switch (routeName) { case '/ViewPostPage': await AuthNav.navigationKey.currentState!.pushReplacementNamed(routeName, arguments: int.parse(result['kmdpWallId'])); break; default: await AuthNav.navigationKey.currentState!.pushNamed("/MainPage"); } } else { await AuthNav.navigationKey.currentState!.pushNamed("/LoginPage"); } } } catch (err, stack) { print(err); print(stack); } } ``` >routes.dart ``` makeRoute( {required BuildContext context, required String routeName, Object? arguments}) { final PageRoute child = _buildRoute(context: context, routeName: routeName, arguments: arguments); return child; } _buildRoute({ required BuildContext context, required String routeName, Object? arguments, }) { switch (routeName) { case '/': return normalPageRoute( context: context, page: ChangeNotifierProvider( create: (context) => StartScreenProvider(), child: StartScreenPage(), ), ); case '/LoginPage': return normalPageRoute( context: context, page: ChangeNotifierProvider( create: (context) => LoginPageProvider(), child: LoginPage(), ), ); case '/ViewPostPage': int kmdpWallId = arguments as int; return normalPageRoute( context: context, page: ChangeNotifierProvider( create: (context) => ViewPostPageProvider(kmdpWallId: kmdpWallId), child: ViewPostPage(), ), ); // case '/AddCommentsPage': // PostData postData = arguments as PostData; // return normalPageRoute( // context: context, // page: ChangeNotifierProvider( // create: (context) => AddCommentsProvider(postData: postData), // child: AddCommentsPage())); // case '/': // return normalPageRoute(context: context, page: ChangeNotifierProvider(create: create)) default: throw 'Route $routeName is not defined'; } } normalPageRoute({ required BuildContext context, required Widget page, }) => MaterialPageRoute( builder: (BuildContext context) => page, maintainState: true, fullscreenDialog: false); ``` >auth_nav.dart ``` static final 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);
}
}
我目前遇到以下问题: 我已经实现了自定义FirebaseMessagingService,并且覆盖了方法onMessageReceived()。此外,当应用程序在后台时,我从getExtras()获取捆绑包 我需要通知内容,以便在db中本地保存 发生了什么: 当应用程序处于后台时,从Firebase控制台发送3个通知 创建了3个状态栏通知 单击其中一个- 你能帮忙吗? 启动器活动代码: 自定义Fi
我正在读取火基数据库的数据。以下是存储在数据库中的数据的快照。 在以“8SS...”开头的快照字符串中,是用户的 uid。以下是用于从 firebase 数据库中检索数据的代码。 用户类包含getter和setters。 错误是只有结论。 如何评估 从值事件中读取时的错误是什么? 我尝试使用这个: 然后调用<code>ref。addListenerForSingleValueEvent()但仍然没
我是初学扑动的。我的flutter应用程序在kotlin上有一个原生的android后台服务,在那里我有一个套接字在运行,每当套接字侦听一些东西时,我就会使用notificationcompat.builder生成一个通知。 但当用户点击通知时,我无法将Flutter应用程序带回前台。 我尝试创建一个pendingintent并将其传递给notificationbuilder setContent
我引用了前台和后台接收firebase通知的答案-->https://stackoverflow.com/A/38451582/12553303 其实下面是我的疑问:-------- 如果我没有为前台条件编码(谈论推送通知),当我的应用程序在后台时,我仍然会得到通知,对吗????-->是的 但是,当im处于前台状态时,我从firebase推送了一个通知-->我不会在状态栏上看到通知,这也是可以的(
手动设置“自动取消”标志 改用builder.build() notificationmanger取消(id)和/或取消所有 使用NotificationCompat.Builder 对setContentIntent使用常规启动意图,而不是手动调用StartActivity
假设我的应用程序包含以下权限摄像头,写内部存储等...