【发布时间】:2020-11-20 01:44:11
【问题描述】:
我有一个 Flutter 应用程序,它使用 Firebase 云消息传递来显示推送通知,非常基本。
main.dart 感觉很重,所以我添加了一个 push_notification_service.dart 文件来处理那里的通知。但是这样做我无法使用通知数据。
我在调试控制台中得到以下信息:(编辑:仅在使用 .then() 时。等待不起作用)
致命:找不到回调,然后是带有我的通知数据的打印语句。
这是 push_notification_service.dart
import 'dart:io';
import 'package:firebase_messaging/firebase_messaging.dart';
class PushNotificationService {
final FirebaseMessaging _fcm;
PushNotificationService(this._fcm);
Future initialise() async {
String initMessage = "default";
if (Platform.isIOS) {
// Request permission if on IOS
_fcm.requestNotificationPermissions(IosNotificationSettings());
}
_fcm.configure(
// Called when the app is in the foreground and a push notif is received
onMessage: (Map<String, dynamic> message) async {
print("Message -Foreground- received: $message"); // This is printed successfully
initMessage = message['notification']['title'];
},
// Called when the app is completely closed and it's opened from
// the push notification directly
onLaunch: (Map<String, dynamic> message) async {
print("Message -Closed- received: $message"); // This is printed successfully
initMessage = message['notification']['title'];
},
// Called when the app is in the background and it's opened from
// the push notification
onResume: (Map<String, dynamic> message) async {
print("Message -Background- received: $message"); // This is printed successfully
initMessage = message['notification']['title'];
},
);
return initMessage;
}
}
这是 main.dart:
import 'package:flutter/material.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import './push_notification_service.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
final FirebaseMessaging _fcm = FirebaseMessaging();
String title = "Notif Title";
String helperText = "Notif Text";
@override
void initState() {
super.initState();
title = await PushNotificationService(_fcm).initialise();
// The following line didn't work too:
// PushNotificationService(_fcm).initialise().then((data) { setState(...) } )
}
@override
Widget build(BuildContext context) {
return MaterialApp( home: Text(title) );
}
}
我最终想将通知标题分配给 main.dart
中的标题变量【问题讨论】: