flutter - 如何在通知中显示图像

标签 flutter dart notifications firebase-cloud-messaging

我使用 firebase 和这些软件包显示通知:

  • firebase_core:^1.1.0
  • firebase_messaging:^10.0.0
  • flutter_local_notifications:^5.0.0+4

我有这段代码,它显示带有标题和正文的通知,但我找不到任何方法来添加通知图像:

initNotification() {
    FirebaseMessaging.onMessage.listen((RemoteMessage message) {
      debugPrint("test notification alert");
      RemoteNotification? notification = message.notification;
      AndroidNotification? android = message.notification?.android;
      debugPrint('title : '+notification!.title.toString());
      debugPrint('notification image : '+notification.android!.imageUrl.toString());
      // debugPrint('title : '+notification.android);
      if (notification != null && android != null) {
        flutterLocalNotificationsPlugin.show(
            notification.hashCode,
            notification.title,
            notification.body,
            NotificationDetails(
              android: AndroidNotificationDetails(
                channel.id,
                channel.name,
                channel.description,
                color: Colors.blue,
                playSound: true,
                icon: '@mipmap/ic_launcher',
              ),
            ));
      }
    });

    FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
      print('A new onMessageOpenedApp event was published!');
      RemoteNotification? notification = message.notification;
      AndroidNotification? android = message.notification?.android;
      if (notification != null && android != null) {
        showDialog(
            context: context,
            builder: (_) {
              return AlertDialog(
                title: Text(notification.title.toString()),
                content: SingleChildScrollView(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [Text(notification.body.toString())],
                  ),
                ),
              );
            });
      }
    });
  }

有什么办法可以显示图像,请帮助我

最佳答案

在监听回调中,您必须检索图像 URL、下载它并将其传递给 AndroidNotificationDetails 或 IOSNotificationDetails。

您可以这样做: 首先获取url

String? _getImageUrl(RemoteNotification notification) {
  if (Platform.isIOS && notification.apple != null) return notification.apple?.imageUrl;
  if (Platform.isAndroid && notification.android != null) return notification.android?.imageUrl;
  return null;
}

然后下载并保存图片

Future<String?> _downloadAndSavePicture(String? url, String fileName) async {
  if (url == null) return null;
  final Directory directory = await getApplicationDocumentsDirectory();
  final String filePath = '${directory.path}/$fileName';
  final http.Response response = await http.get(Uri.parse(url));
  final File file = File(filePath);
  await file.writeAsBytes(response.bodyBytes);
  return filePath;
}

构建通知详细信息

NotificationDetails _buildDetails(String title, String body, String? picturePath, bool showBigPicture) {
  final AndroidNotificationDetails androidPlatformChannelSpecifics = AndroidNotificationDetails(
    _channel.id,
    _channel.name,
    channelDescription: _channel.description,
    styleInformation: _buildBigPictureStyleInformation(title, body, picturePath, showBigPicture),
    importance: _channel.importance,
    icon: "notification_icon",
  );
    final IOSNotificationDetails iOSPlatformChannelSpecifics = IOSNotificationDetails(
    attachments: [if (picturePath != null) IOSNotificationAttachment(picturePath)],
  );
  final NotificationDetails details = NotificationDetails(
    android: androidPlatformChannelSpecifics,
    iOS: iOSPlatformChannelSpecifics,
  );
  return details;
}

最后显示通知

await _flutterNotificationPlugin.show(
  0,
  title,
  body,
  details,
);

编辑(在下面添加代码块):

BigPictureStyleInformation? _buildBigPictureStyleInformation(
    String title,
    String body,
    String? picturePath,
    bool showBigPicture,
  ) {
    if (picturePath == null) return null;
    final FilePathAndroidBitmap filePath = FilePathAndroidBitmap(picturePath);
    return BigPictureStyleInformation(
      showBigPicture ? filePath : const FilePathAndroidBitmap("empty"),
      largeIcon: filePath,
      contentTitle: title,
      htmlFormatContentTitle: true,
      summaryText: body,
      htmlFormatSummaryText: true,
    );
  }

它有点长,但是使用这个插件没有最短的方法来做到这一点。

关于flutter - 如何在通知中显示图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71336928/

相关文章:

firebase - Flutter/Firebase - 类型 'Future<int>' 不是类型 'int' 的子类型

android - 如何防止通知栏在新通知上滚动动画

flutter - flutter 的小怪未检测到

firebase - Flutter Firebase Google 登录无法正常工作。选择账户后停止

firebase - 在 Flutter ListView 中删除 Firestore 数据

android - 为什么 ListView 不显示用户输入的文本

iphone - 每隔x分钟在后台检查一次条件,如果为true,则发送通知

php - 显示已读和未读通知

flutter - 流生成器。错误状态 : Stream has already been listened to

flutter - 将 OneSignal 与 Flutter 结合使用