首页 > 解决方案 > Icon问题localNotificationsPlugin,如何正确添加app Icon

问题描述

我已经在颤振应用程序中实现了本地推送通知。这个插件一开始运行顺畅。当我运行flutter clean并卸载 android Emulator 上的应用程序以使用flutter run. 这样做后,应用程序在启动时崩溃。

在调试模式下运行应用程序时,显示错误发生在await localNotificationsPlugin.initialize. 调试器显示下面的语句。

Exception has occurred.
PlatformException (PlatformException(INVALID_ICON, The resource ic_launcher could not be found. Please make sure it has been added as a drawable resource to your Android head project., null))

下面的代码显示了我是如何实现 localNotificationsPlugin 的。

FlutterLocalNotificationsPlugin localNotificationsPlugin =
      FlutterLocalNotificationsPlugin();
  initializeNotifications() async {
    var initAndroid = AndroidInitializationSettings('ic_launcher');
    var initIOS = IOSInitializationSettings();
    var initSettings = InitializationSettings(initAndroid, initIOS);

    await localNotificationsPlugin.initialize(
      initSettings,
      onSelectNotification: gotToNotificationsPage,
    );
  }

  @override
  void initState() {
    super.initState();
    initializeNotifications();
    showNotification();
  }

  Future singleNotification(
      DateTime datetime, String message, String subtext, int hashcode,
      {String sound}) async {
    var androidChannel = AndroidNotificationDetails(
      'channel-id',
      'channel-name',
      'channel-description',
      importance: Importance.Max,
      priority: Priority.Max,
    );

    var iosChannel = IOSNotificationDetails();
    var platformChannel = NotificationDetails(androidChannel, iosChannel);
    localNotificationsPlugin.schedule(
        hashcode, message, subtext, datetime, platformChannel,
        payload: hashcode.toString());
  }

  showNotification() async {
    DateTime now = DateTime.now().toUtc().add(
          Duration(seconds: 5),
        );

    await singleNotification(
      now,
      'Notification',
      'This is a notification',
      98123871,
    );
  }

  Future gotToNotificationsPage(String payload) {
    return Navigator.pushNamed(context, '/notifications');
  }

请注意,问题出在await localNotificationsPlugin.initialize我未能正确分配应用程序图标。谢谢你。

标签: androidflutterdartpush-notificationscheduled-tasks

解决方案


要设置自定义图标,您可以在里面添加一个 app_icon.png android/app/src/res/drawable,然后使用

const AndroidInitializationSettings initializationSettingsAndroid =
    AndroidInitializationSettings('app_icon');`

否则,如果您想使用默认应用程序图标,您可以在 AndroidInitializationSettings 上设置应用程序图标@mipmap/ic_launcher

如果您不确定从哪里开始,可以尝试GitHub 上插件提供的示例。


推荐阅读