我在特定时间从我的服务器接收通知以向用户显示通知。但是,每当我的设备收到来自 Firebase Cloud Messaging 的消息时,FlutterLocalNotificationsPlugin
最终都会显示两条通知,如下所示。
我已经确认我从我的服务器收到了一条通知,我认为它只是在前端的某个地方处理不正确。
这是我在后台调用它的代码
main
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
// If you're going to use other Firebase services in the background, such as Firestore,
// make sure you call `initializeApp` before using other Firebase services.
await Firebase.initializeApp();
print('Handling a background message ${message.messageId}');
if (message.notification != null) {
print(message.notification.title);
print(message.notification.body);
flutterLocalNotificationsPlugin.show(
message.notification.hashCode,
message.notification.title,
message.notification.body,
NotificationDetails(
android: AndroidNotificationDetails(
channel.id,
channel.name,
channel.description,
icon: 'launch_background',
),
iOS: IOSNotificationDetails()
));
}
// Create a notification for this
}
const AndroidNotificationChannel channel = AndroidNotificationChannel(
'high_importance_channel', // id
'High Importance Notifications', // title
'This channel is used for important notifications.', // description
importance: Importance.high,
);
final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();
// Starting FlutterFire through the suggestion found here
// https://firebase.flutter.dev/docs/overview
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
/// Create an Android Notification Channel.
/// We use this channel in the `AndroidManifest.xml` file to override the
/// default FCM channel to enable heads up notifications.
await flutterLocalNotificationsPlugin
.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin>()
?.createNotificationChannel(channel);
/// Update the iOS foreground notification presentation options to allow
/// heads up notifications.
await FirebaseMessaging.instance.setForegroundNotificationPresentationOptions(
alert: true,
badge: true,
sound: true,
);
runApp(MyApp());
}
class MyApp extends StatefulWidget {
MyApp({Key key}) : super(key: key);
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
User _user;
FirebaseAnalytics analytics;
bool _error = false;
void _handleLogin(User user) {
// print("Handle Login");
setState(() {
_user = user;
});
}
@override
void initState() {
super.initState();
// if we opened the app through a notification, it will send us via this
FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
print('On Message Opened!');
print(message);
});
}
@override
Widget build(BuildContext context) {
}
}