Flutter 和 Firebase 消息传递:从通知中提取数据

时间:2021-04-11 14:35:57

标签: firebase flutter firebase-cloud-messaging

当用户点击通知时,我如何让 Flutter 知道通知的内容是什么?我已经尝试了文档 (https://firebase.flutter.dev/docs/messaging/notifications#handling-interaction) 中给出的示例,但它似乎不适用于我的代码:

main.dart:

main()  {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> with WidgetsBindingObserver {
  @override
  void initState() {
    super.initState();
    pushNotifactionsInitialization();
    ...
  }
}
String notificationMessage;

void pushNotifactionsInitialization() async {
 FirebaseMessaging messaging = FirebaseMessaging.instance;

 NotificationSettings settings = await messaging.requestPermission(
   alert: true,
   announcement: false,
   badge: true,
   carPlay: false,
   criticalAlert: false,
   provisional: false,
   sound: true,
 );

 // Get any messages which caused the application to open from
 // a terminated state.
 RemoteMessage initialMessage = await FirebaseMessaging.instance.getInitialMessage();
 if (initialMessage != null) {
    showToast(initialMessage.toString()); //Displays Toast
 }

 // Also handle any interaction when the app is in the background via a
 // Stream listener
 FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
   if (message != null) {
     showToast(message.toString());
   }
 });
} 

0 个答案:

没有答案