简体   繁体   English

flutter_local_notifications 插件未在通知中显示大图像

[英]flutter_local_notifications plugin not showing the big image in notification

I need to make like this notification我需要像这样通知

在此处输入图像描述

My Output code我的输出代码

在此处输入图像描述

my Pubspec.yaml file.我的 Pubspec.yaml 文件。 I am using latest version of flutter_local_notifications我正在使用最新版本的 flutter_local_notifications

  flutter_local_notifications: ^9.2.0

This is my Notification Controller code这是我的通知控制器代码

import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/services.dart';
import 'package:http/http.dart' as http;
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:image/image.dart' as image;
import 'package:path_provider/path_provider.dart';

class NotificationService {
  static final NotificationService _notificationService =
      NotificationService._internal();

  final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
      FlutterLocalNotificationsPlugin();

  factory NotificationService() {
    return _notificationService;
  }

  NotificationService._internal();
  Future<void> init(
      Function(int, String?, String?, String?)?
          onDidReceiveLocalNotification) async {
    const AndroidInitializationSettings initializationSettingsAndroid =
        AndroidInitializationSettings('@mipmap/launcher_icon');

    final IOSInitializationSettings initializationSettingsIOS =
        IOSInitializationSettings(
      requestAlertPermission: false,
      requestBadgePermission: false,
      requestSoundPermission: false,
      onDidReceiveLocalNotification:
          (int id, String? title, String? body, String? payload) async {},
    );
    final InitializationSettings initializationSettings =
        InitializationSettings(
      android: initializationSettingsAndroid,
      iOS: initializationSettingsIOS,
    );
    await flutterLocalNotificationsPlugin.initialize(
      initializationSettings,
      onSelectNotification: (String? payload) async {
        if (payload != null) {
          print('notification payload: $payload');
        }
      },
    );
  }

  Future selectNotification(String? payload) async {
    print('selectNotification: $payload');
  }

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

  Future showNotify({
    required String body,
    required String image,
  }) async {
    final String largeIconPath = await _downloadAndSaveFile(
      'https://via.placeholder.com/48x48',
      'largeIcon',
    );
    final String bigPicturePath = await _downloadAndSaveFile(
      image,
      'bigPicture',
    );

    await flutterLocalNotificationsPlugin.show(
      123,
      'New Buisness Sutra Updated',
      body,
      NotificationDetails(
        android: AndroidNotificationDetails(
          'big text channel id',
          'big text channel name',
          ongoing: true,
          priority: Priority.max,
          largeIcon: FilePathAndroidBitmap(largeIconPath),
          channelDescription: 'big text channel description',
          styleInformation: BigPictureStyleInformation(
            FilePathAndroidBitmap(bigPicturePath),
            hideExpandedLargeIcon: false,
            contentTitle: 'overridden <b>big</b> content title',
            htmlFormatContentTitle: true,
            summaryText: 'summary <i>text</i>',
            htmlFormatSummaryText: true,
          ),
        ),
      ),
      payload: 'data',
    );
  }
}

I initialized the firebase and notification on my main.dart file我在 main.dart 文件中初始化了 firebase 和通知


void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  if (!kIsWeb) {
    await Firebase.initializeApp();
    firebaseCloudMessagingListeners();
    await NotificationService().init();
  }
  runApp(const MyApp());
}

firebaseCloudMessagingListeners() {
  FirebaseMessaging.onBackgroundMessage(_messageHandler);
  FirebaseMessaging.onMessage.listen((RemoteMessage message) {
    print(message);
    _messageHandler(message);
  });
  FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
    print("Message opened");
  });
}

Future<void> _messageHandler(RemoteMessage message) async {
  Map<String, dynamic> data = message.data;
  print(data);
  await NotificationService().showNotify(
    body: data["body"],
    image: data["image"],
  );
}

The firebase_messaging plugin works fine. firebase_messaging 插件工作正常。 The problem is with the big picture on the notification from flutter_local_notifications.问题在于来自 flutter_local_notifications 的通知的大图。 I download the image by using path_provider and http.我使用 path_provider 和 http 下载图像。 also this image succesfully downloaded on my app External storage directory.此图像也已成功下载到我的应用程序外部存储目录中。 But not shown on the notification但通知上没有显示

/storage/emulated/0/Android/data/in.myapp.dhrona/files/largeIcon.png /storage/emulated/0/Android/data/in.myapp.dhrona/files/bigIcon.png /storage/emulated/0/Android/data/in.myapp.dhrona/files/largeIcon.png /storage/emulated/0/Android/data/in.myapp.dhrona/files/bigIcon.png

Any solutions for this issue此问题的任何解决方案

To show network image,展示网络形象,

    final http.Response response = await http.get(Uri.parse(URL));
    BigPictureStyleInformation bigPictureStyleInformation =
        BigPictureStyleInformation(
      ByteArrayAndroidBitmap.fromBase64String(base64Encode(image)),
      largeIcon: ByteArrayAndroidBitmap.fromBase64String(base64Encode(image)),
    );
    flutterLocalNotificationsPlugin.show(
      Random().nextInt(1000),
      title,
      description,
      NotificationDetails(
        android: AndroidNotificationDetails(channel.id, channel.name,
            channelDescription: channel.description,
            importance: Importance.high,
            styleInformation: bigPictureStyleInformation),
      ),
    );

To show local image,要显示本地图像,

    final String filePath = '${directory.path}/$fileName';
    final BigPictureStyleInformation bigPictureStyleInformation =
        BigPictureStyleInformation(FilePathAndroidBitmap(filePath),
            largeIcon: FilePathAndroidBitmap(filePath));
    flutterLocalNotificationsPlugin.show(
      Random().nextInt(1000),
      title,
      description,
      NotificationDetails(
        android: AndroidNotificationDetails(channel.id, channel.name,
            channelDescription: channel.description,
            importance: Importance.high,
            styleInformation: bigPictureStyleInformation),
      ),
    );

With AwesomeNotifications I don't need to download.使用 AwesomeNotifications,我不需要下载。 I just give the url like below:我只是给出如下网址:

  Future<void> showNotificationChatMessage(
      RemoteMessage message, MyMessage myMessage) async {
    final chatId = message.data['chatId'];
    NotificationContent? notificationContent;
    if (myMessage.type == MyMessageType.text ||
        myMessage.replyType == MyMessageReplyType.text) {
      notificationContent = NotificationContent(
          id: 10,
          channelKey: 'basic_channel',
          title: message.data['title'].toString(),
          body: message.data['body'].toString(),
          payload: {'chatId': chatId.toString()});
    } else if (myMessage.type == MyMessageType.image ||
        myMessage.replyType == MyMessageReplyType.image) {
      notificationContent = NotificationContent(
          id: 11,
          channelKey: 'big_picture',
          title: message.data['title'].toString(),
          body: 'Image',
          bigPicture: myMessage.message,
          showWhen: true,
          displayOnBackground: true,
          payload: {'chatId': chatId.toString()},
          notificationLayout: NotificationLayout.BigPicture);
    }
    if (notificationContent != null) {
      AwesomeNotifications().createNotification(content: notificationContent);
    }
  }

Although the answer by @Vignesh works, here are some improvements to that answer:虽然@Vignesh 的答案有效,但这里有一些对该答案的改进:

  • response is not used in the example示例中未使用响应
  • there is no need to set the "largeIcon" property with the same image data as the big image because it will show the same image two times in the notification when the notification is expanded.不需要将“largeIcon”属性设置为与大图相同的图像数据,因为当通知展开时,它会在通知中显示两次相同的图像。

the final answer should look like this:最终答案应该是这样的:

final http.Response response = await http.get(Uri.parse(imageUrl));
        bigPictureStyleInformation = BigPictureStyleInformation(
            ByteArrayAndroidBitmap.fromBase64String(base64Encode(response.bodyBytes)));

      flutterLocalNotificationsPlugin.show(
          notification.hashCode,
          notification.title ?? 'APP_NAME',
          notification.body,
          NotificationDetails(
            android: AndroidNotificationDetails(
              channel.id,
              channel.name,
              channelDescription: channel.description,
              styleInformation: bigPictureStyleInformation,
              // other properties...
            ),
          )
      );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 计划通知未显示(Flutter_local_notifications) - scheduled notifications not showing (Flutter_local_notifications) 使用 flutter_local_notifications 安排通知 - Schedule notification using flutter_local_notifications Flutter 本地通知正文未显示所有通知文本(flutter_local_notifications 包) - Flutter local notification body not showing all notification text (flutter_local_notifications package) 有没有办法使用 flutter_local_notifications 跳过重复通知? - Is there a way to skip a recurring notification using flutter_local_notifications? flutter_local_notifications 不显示通知(仅限IOS) - flutter_local_notifications does not show the notification(IOS only) flutter_local_notifications onNotificationReceived 方法 - Flutter - flutter_local_notifications onNotificationReceived method - Flutter 如何使用flutter插件显示多个通知:flutter_local_notifications - How to display multiple notifications using flutter plugin : flutter_local_notifications 使用 flutter_local_notifications 插件时,挂起的通知在重启后被取消 - When using the flutter_local_notifications plugin, pending notifications are cancelled after a reboot flutter_local_notifications 对我不起作用 - flutter_local_notifications not working for me flutter_local_notifications 路由全屏 - flutter_local_notifications route fullscreen
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM