【问题标题】:Can't get Notifications Icon on the notifications Pop up in Android Flutter with FCM messaging无法在通知上获取通知图标 使用 FCM 消息在 Android Flutter 中弹出
【发布时间】:2021-03-11 08:27:15
【问题描述】:

一段时间后,我能够设置在前台和后台启用的通知 这是我实现本地和 FCM 通知的代码,但即使我在通知中设置了我的图标,也没有显示。

final FirebaseMessaging firebaseMessaging = FirebaseMessaging();
  final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
  FlutterLocalNotificationsPlugin();


  
  @override
  void initState() {
    super.initState();
    registerNotification();
    configLocalNotification();
    FlutterBackground.initialize();
  }



  void registerNotification() {
    firebaseMessaging.requestNotificationPermissions();

    firebaseMessaging.configure(onMessage: (Map<String, dynamic> message) {
      print('onMessage: $message');
      Platform.isAndroid
          ? showNotification(message['notification'])
          : showNotification(message['aps']['alert']);
      return ;
    }, onResume: (Map<String, dynamic> message) {
      print('onResume: $message');
      return Navigator.push(
          context,
          MaterialPageRoute(
              builder: (context) => NotificationsScreen()));
    },         onLaunch: (Map<String, dynamic> message) {
      print('onLaunch: $message');
      return;
    },
        onBackgroundMessage: myBackgroundMessageHandler
    );



    firebaseMessaging.getToken().then((token) {
      print('token: $token');
      FirebaseFirestore.instance
          .collection('Consultant')
          .doc(firebaseUser.uid)
          .update({'deviceToken': token});
    }).catchError((err) {
      //Fluttertoast.showToast(msg: err.message.toString());
    });
  }

  Future selectNotification(String payload) async {
    if (payload != null) {
      debugPrint('notification payload: $payload');
    }
    await Navigator.push(
      context,
      MaterialPageRoute<void>(builder: (context) => NotificationsScreen(payload: payload,)),
    );
  }

  void showNotification(message) async {
    var androidPlatformChannelSpecifics = new AndroidNotificationDetails(
      Platform.isAndroid
          ? 'it.wytex.vibeland_pro_app'
          : 'it.wytex.vibeland_pro_app',
      'Vibeland Pro',
      'Vibeland Pro',
      playSound: true,
      enableVibration: true,
      importance: Importance.max,
      priority: Priority.high,
    );
    var iOSPlatformChannelSpecifics = new IOSNotificationDetails();
    var platformChannelSpecifics = new NotificationDetails(
        android: androidPlatformChannelSpecifics, iOS: iOSPlatformChannelSpecifics);

    print(message);
    print(message['body'].toString());
    print(json.encode(message));

    // await flutterLocalNotificationsPlugin.show(2, message['title'].toString(),
    //     message['body'].toString(), platformChannelSpecifics,
    //     payload: json.encode(message));

    await flutterLocalNotificationsPlugin.show(
      3, '???? Hai ricevuto un messaggio ???? ', 'Controlla subito le Tue notifiche ????????', platformChannelSpecifics,
      payload: 'item x',
    );
  }

  void configLocalNotification() {
    var initializationSettingsAndroid =
    new AndroidInitializationSettings('@mipmap/ic_launcher');
    var initializationSettingsIOS = new IOSInitializationSettings(
      requestAlertPermission: true,
      requestBadgePermission: true,
      requestSoundPermission: true,
    );
    var initializationSettings = new InitializationSettings(
        android: initializationSettingsAndroid, iOS: initializationSettingsIOS);
    flutterLocalNotificationsPlugin.initialize(initializationSettings);
  }

如你所见,我应该得到@mipmap/ic_launcher 图标,但它没有...

我还需要在我的 firebase 函数中指定吗?

const functions = require("firebase-functions");
const admin = require("firebase-admin");

admin.initializeApp(functions.config().firebase);

const fcm = admin.messaging();

exports.sendNotification = functions.firestore
    .document("Notifications/{id}")
    .onCreate((snapshot) => {
      const name = snapshot.get("name");
      const subject = snapshot.get("subject");
      const token = snapshot.get("token");

      const payload = {
        notification: {
          title: "" + name,
          body: "" + subject,
          sound: "default",
        },
        data: {
          click_action: "FLUTTER_NOTIFICATION_CLICK",
        },
      };

      return fcm.sendToDevice(token, payload);
    });

这也是我的 AndroidManifest...


<application
        android:name=".Application"
        android:label="My APP"
        android:icon="@mipmap/ic_launcher">
        <activity
            android:showWhenLocked="true"
            android:name="io.flutter.embedding.android.FlutterActivity"
            android:launchMode="singleTop"
            android:theme="@style/LaunchTheme"
            android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
            android:hardwareAccelerated="true"
            android:windowSoftInputMode="adjustResize">
            <!-- Specifies an Android theme to apply to this Activity as soon as
                 the Android process has started. This theme is visible to the user
                 while the Flutter UI initializes. After that, this theme continues
                 to determine the Window background behind the Flutter UI. -->
            <meta-data
              android:name="io.flutter.embedding.android.NormalTheme"
              android:resource="@style/NormalTheme"
              />
            <!-- Displays an Android View that continues showing the launch screen
                 Drawable until Flutter paints its first frame, then this splash
                 screen fades out. A splash screen is useful to avoid any visual
                 gap between the end of Android's launch screen and the painting of
                 Flutter's first frame. -->
            <meta-data
              android:name="io.flutter.embedding.android.SplashScreenDrawable"
              android:resource="@drawable/launch_background"
              />
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
            <intent-filter>
                <action android:name="FLUTTER_NOTIFICATION_CLICK" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED"/>
                <action android:name="android.intent.action.MY_PACKAGE_REPLACED"/>
            </intent-filter>

        </activity>
        <!-- Don't delete the meta-data below.
             This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
        <meta-data
            android:name="flutterEmbedding"
            android:requestLegacyExternalStorage="true"
            android:value="2" />
    </application>

我只是得到一个背景灰色方块作为图标... 我尝试添加```

<meta-data
                android:name="com.google.firebase.messaging.default_notification_icon"
                android:resource="@drawable/ic_stat_ic_notification" />
          
            <meta-data
                android:name="com.google.firebase.messaging.default_notification_color"
                android:resource="@color/colorAccent" />

但我在构建 APK 时出错:

Plugin with id 'com.android.library' not found

【问题讨论】:

    标签: android firebase flutter firebase-cloud-messaging


    【解决方案1】:

    只需尝试将此库添加到您的 launcher icon

    • 将 flutter_launcher_icons: ^0.9.0 添加到您的 pubspec.yaml
    • 运行 flutter pub get
    • uder dev_dependencies:添加此代码
    • 颤振酒吧获取
    • flutter pub 运行 flutter_launcher_icons:main

    之后尝试卸载并重新安装并尝试再次发送通知,图标应该可见

    dev_dependencies:
      flutter_launcher_icons: "^0.8.0"
    
    flutter_icons:
      android: "launcher_icon"
      ios: true
      image_path: "assets/icon/icon.png"

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-08
      • 2023-02-14
      • 2020-09-14
      • 1970-01-01
      • 1970-01-01
      • 2019-07-29
      相关资源
      最近更新 更多