gpt4 book ai didi

带有本地通知和警报的 Flutter- FCM

转载 作者:行者123 更新时间:2023-12-05 03:46:53 32 4
gpt4 key购买 nike

这是我第一次使用 Flutter 测试 FCM。我检查了一些来自 GitHub 的 SO 问题和文档。

我能够发送通知,当应用程序未运行时它们会被发送。

如果应用程序正在运行或在后台,则消息不可见。

我已经在 main.dart 文件中添加了代码,但不确定这是不是正确的方法。

编辑:这是用于 onResume 的:

{notification: {}, data: {badge: 1, collapse_key: com.HT, google.original_priority: high, google.sent_time: 1623238, google.delivered_priority: high, sound: default, google.ttl: 2419200, from: 71374876, body: Body, title: Title, click_action: FLUTTER_NOTIFICATION_CLICK, google.message_id: 0:50a56}}

在下面的代码中,我尝试将本地通知与 FCM 结合使用。

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

class _MyAppState extends State<MyApp> {
final FirebaseMessaging _firebaseMessaging = FirebaseMessaging();
FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
new FlutterLocalNotificationsPlugin();

@override
void initState() {
var initializationSettingsAndroid =
new AndroidInitializationSettings('@mipmap/ic_launcher');
var initializationSettingsIOS = new IOSInitializationSettings();
var initializationSettings = new InitializationSettings(
android: initializationSettingsAndroid, iOS: initializationSettingsIOS);
flutterLocalNotificationsPlugin.initialize(initializationSettings,
onSelectNotification: onSelectNotification);
_firebaseMessaging.configure(
onMessage: (Map<String, dynamic> message) async {
showNotification(
message['notification']['title'], message['notification']['body']);
print("onMessage: $message");
},
onLaunch: (Map<String, dynamic> message) async {
print("onLaunch: $message");
// Navigator.pushNamed(context, '/notify');
ExtendedNavigator.of(context).push(
Routes.bookingQRScan,
);
},
onResume: (Map<String, dynamic> message) async {
print("onResume: $message");
},
);
}

Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
primarySwatch: Colors.blue,
),
debugShowCheckedModeBanner: false,
home: AnimatedSplashScreen(), //SplashScreen()

builder: ExtendedNavigator.builder<a.Router>(router: a.Router()),
);
}

Future onSelectNotification(String payload) async {
showDialog(
context: context,
builder: (_) {
return new AlertDialog(
title: Text("PayLoad"),
content: Text("Payload : $payload"),
);
},
);
}

void showNotification(String title, String body) async {
await _demoNotification(title, body);
}

Future<void> _demoNotification(String title, String body) async {
var androidPlatformChannelSpecifics = AndroidNotificationDetails(
'channel_ID', 'channel name', 'channel description',
importance: Importance.max,
playSound: false, //true,
//sound: 'sound',
showProgress: true,
priority: Priority.high,
ticker: 'test ticker');

//var iOSChannelSpecifics = IOSNotificationDetails();
var platformChannelSpecifics =
NotificationDetails(android: androidPlatformChannelSpecifics);
await flutterLocalNotificationsPlugin
.show(0, title, body, platformChannelSpecifics, payload: 'test');
}
}

错误

This is when my app is running on foreground. E/FlutterFcmService(14434): Fatal: failed to find callback
W/FirebaseMessaging(14434): Missing Default Notification Channel metadata in AndroidManifest. Default value will be used.
W/ConnectionTracker(14434): Exception thrown while unbinding
W/ConnectionTracker(14434): java.lang.IllegalArgumentException: Service not registered: lu@fb04880
Notification is visible in notification center. Now i am clicking on it and app get terminated.
and new instance of app is running and below is the return code. I/flutter (14434): onResume: {notification: {}, data: {badge: 1, collapse_key: com.HT, google.original_priority: high, google.sent_time: 1607733798, google.delivered_priority: high, sound: default, google.ttl: 2419200, from: 774876, body: Body, title: Title, click_action: FLUTTER_NOTIFICATION_CLICK, google.message_id: 0:1607573733816296%850a56}}
E/FlutterFcmService(14434): Fatal: failed to find callback
W/ConnectionTracker(14434): Exception thrown while unbinding

编辑 2:我做了更多挖掘并提出了以下代码。

final FirebaseMessaging _fcm = FirebaseMessaging();

FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();

var initializationSettingsAndroid;
var initializationSettingsIOS;
var initializationSettings;

void _showNotification() async {
//await _buildNotification();
}

Future<dynamic> myBackgroundMessageHandler(Map<String, dynamic> message) {
if (message.containsKey('data')) {
// Handle data message
final dynamic data = message['data'];
}

if (message.containsKey('notification')) {
// Handle notification message

final dynamic notification = message['notification'];
}

// Or do other work.
}

Future<void> _createNotificationChannel(
String id, String name, String description) async {
final flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
var androidNotificationChannel = AndroidNotificationChannel(
id,
name,
description,
importance: Importance.max,
playSound: true,
// sound: RawResourceAndroidNotificationSound('not_kiddin'),
enableVibration: true,
);
await flutterLocalNotificationsPlugin
.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin>()
?.createNotificationChannel(androidNotificationChannel);
}

Future<void> _buildNotification(String title, String body) async {
var androidPlatformChannelSpecifics = AndroidNotificationDetails(
'my_channel', 'Channel Name', 'Channel Description.',
importance: Importance.max,
priority: Priority.high,
// playSound: true,
enableVibration: true,
// sound: RawResourceAndroidNotificationSound('not_kiddin'),
ticker: 'noorderlicht');
//var iOSChannelSpecifics = IOSNotificationDetails();
var platformChannelSpecifics =
NotificationDetails(android: androidPlatformChannelSpecifics);

await flutterLocalNotificationsPlugin
.show(0, title, body, platformChannelSpecifics, payload: 'payload');
}

@override
void initState() {
super.initState();

initializationSettingsAndroid =
AndroidInitializationSettings('@mipmap/ic_launcher');
initializationSettingsIOS = IOSInitializationSettings(
onDidReceiveLocalNotification: onDidReceiveLocalNotification);

initializationSettings =
InitializationSettings(android: initializationSettingsAndroid);
// initializationSettingsAndroid, initializationSettingsIOS);

_fcm.requestNotificationPermissions();

_fcm.configure(
onMessage: (Map<String, dynamic> message) async {
print(message);
flutterLocalNotificationsPlugin.initialize(initializationSettings,
onSelectNotification: onSelectNotification);

//_showNotification();
Map.from(message).map((key, value) {
print(key);
print(value);
print(value['title']);
_buildNotification(value['title'], value['body']);
});
},
onLaunch: (Map<String, dynamic> message) async {
print("onLaunch: $message");
},
onResume: (Map<String, dynamic> message) async {
print("onResume: $message");
print(message['data']['title']);
//AlertDialog(title: message['data']['title']);
ExtendedNavigator.of(context).push(
Routes.bookingQRScan,
);
//_showNotification();
},
);
}

Future onDidReceiveLocalNotification(
int id, String title, String body, String payload) async {
// display a dialog with the notification details, tap ok to go to another page
showDialog(
context: context,
builder: (BuildContext context) => CupertinoAlertDialog(
title: Text(title),
content: Text(body),
actions: [
CupertinoDialogAction(
isDefaultAction: true,
child: Text('Ok'),
onPressed: () {},
)
],
),
);
}

Future onSelectNotification(String payload) async {
if (payload != null) {
debugPrint('Notification payload: $payload');
}
}

@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
primarySwatch: Colors.blue,
),
debugShowCheckedModeBanner: false,
home: AnimatedSplashScreen(), //SplashScreen()

builder: ExtendedNavigator.builder<a.Router>(router: a.Router()),
);
}

使用上面的代码,我可以在通知栏中看到通知,但是我想重定向的 onresume 部分不起作用。不知道为什么。

我还想在 onmeesage 和 onresume 事件中显示警告框。

最佳答案

您的负载必须正确,负载内的notificationdata 对象必须包含titlebody key 。当您的应用程序在 notification 键中关闭时,您将得到 titlebody null 在这种情况下,您应该在侧面数据键中包含 title 和 body .

{notification: {title: title, body: test}, data: {notification_type: Welcome, body: body, badge: 1, sound: , title: farhana mam, click_action: FLUTTER_NOTIFICATION_CLICK, message: H R U, category_id: 2, product_id: 1, img_url: }}

并且不要将标题和正文设为空

void showNotification(Map<String, dynamic> msg) async {
//{notification: {title: title, body: test}, data: {notification_type: Welcome, body: body, badge: 1, sound: , title: farhana mam, click_action: FLUTTER_NOTIFICATION_CLICK, message: H R U, category_id: 2, product_id: 1, img_url: }}
print(msg);
print(msg['data']['title']);
var title = msg['data']['title'];
var msge = msg['data']['body'];

var android = new AndroidNotificationDetails(
'channel id', 'channel NAME', 'CHANNEL DESCRIPTION',
priority: Priority.High, importance: Importance.Max);
var iOS = new IOSNotificationDetails();
var platform = new NotificationDetails(android, iOS);
await flutterLocalNotificationsPlugin.show(0, title, msge, platform,
payload: msge);
}

用于重定向

FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = new FlutterLocalNotificationsPlugin();
var android = new AndroidInitializationSettings('@mipmap/ic_launcher');
var iOS = new IOSInitializationSettings();
var initSetttings = new InitializationSettings(android, iOS);
flutterLocalNotificationsPlugin.initialize(initSetttings, onSelectNotification: onSelectNotification);
firebaseCloudMessaging_Listeners();

Future onSelectNotification(String payload) async {
if (payload != null) {
debugPrint('notification payload:------ ${payload}');
await Navigator.push(
context,
new MaterialPageRoute(builder: (context) => NotificationListing()),
).then((value) {});
}

}

在'onSelectNotification'中,你可以在字符串参数中传递你的条件,你可以重定向

(可选,但推荐)如果想在用户点击系统托盘中的通知时在您的应用中收到通知(通过 onResume 和 onLaunch,见下文),请在您的 android/标签中包含以下 intent-filter应用程序/src/main/AndroidManifest.xml:

关于带有本地通知和警报的 Flutter- FCM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65166526/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com