如何解决flutter_local_notifications PlatformException错误?

时间:2020-02-17 16:01:42

标签: android ios flutter dart

我第一次在项目中使用flutter_local_notifications软件包。

遵循pub.dev网站中文档中给出的代码。但是问题是当我按下应该触发通知的按钮时,它导致了PlatformException错误。

错误

E/flutter (15180): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: PlatformException(error, Attempt to invoke virtual method 'int java.lang.Integer.intValue()' on a null object reference, null)
E/flutter (15180): #0      StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:569:7)
E/flutter (15180): #1      MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:318:33)
E/flutter (15180): <asynchronous suspension>
E/flutter (15180): #2      FlutterLocalNotificationsPlugin.show (package:flutter_local_notifications/src/flutter_local_notifications.dart:120:20)
E/flutter (15180): <asynchronous suspension>
E/flutter (15180): #3      _NewsfeedState.showNotification (package:news_app/screens/newsfeed_screen.dart:129:43)

代码如下。

initState()

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

    var android = AndroidInitializationSettings('mipmap-hdpi/ic_launcher.png');
    var ios = IOSInitializationSettings();
    var initSettings = InitializationSettings(android, ios);
    flutterLocalNotificationsPlugin.initialize(initSettings, onSelectNotification: onSelectNotification);

}

onSelectNotification():按下通知时会显示一个对话框。

Future onSelectNotification(String payload) {
    showDialog(context: context, builder: (_) => AlertDialog(
      title: Text("Notfication"),
      content: Text("This is notification"),
    ));
  }

主窗口小部件:出于测试目的,我正在使用此Press按钮来检查通知是否有效。


  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        RaisedButton(
          onPressed: showNotification,
          child: Text(
              "Press"
          ),
        ),
      ],
    );
  }

showNotification()

showNotification() async {
    var android = AndroidNotificationDetails(
        'channel id',
        'channel NAME',
        'CHANNEL DESCRIPTION',
        importance: Importance.Max,
        priority: Priority.High,
        ticker: 'ticker'
    );
    var ios = IOSNotificationDetails();
    var platform = NotificationDetails(android, ios);
    await flutterLocalNotificationsPlugin.show(0, "New Notification", "I'm notification", 
    platform, payload: "It works");
  }

我发现有一个关于该错误的question,但是它提供的解决方案对我没有用。

我几次尝试更改flutter_local_notifications软件包的版本,但没有用。

然后追溯错误中显示的文件,以查看究竟是什么引起了null值。

在文件platform_channel.dart的{​​{1}}内,我尝试打印invokeMethod<T>(String method, [dynamic arguments])method来查看即将出现的arguments。从null中调用此方法。

invokeMethod(字符串方法,[动态参数])

flutter_local_notifications.dart

自变量的输出为

@optionalTypeArgs Future<T> invokeMethod<T>(String method, [ dynamic arguments ]) async { assert(method != null); final ByteData result = await binaryMessenger.send( name, codec.encodeMethodCall(MethodCall(method, arguments)), ); print(arguments); print(method); if(result == null) { throw MissingPluginException('No implementation found for method $method on channel $name'); } final T typedResult = codec.decodeEnvelope(result); return typedResult; }

您可以看到I/flutter (15180): {id: 0, title: New News!, body: I'm news., platformSpecifics: {icon: null, channelId: channel id, channelName: channel NAME, channelDescription: CHANNEL DESCRIPTION, channelShowBadge: true, channelAction: 0, importance: 5, priority: 1, playSound: true, sound: null, enableVibration: true, vibrationPattern: null, style: 0, styleInformation: {htmlFormatContent: false, htmlFormatTitle: false}, groupKey: null, setAsGroupSummary: null, groupAlertBehavior: 0, autoCancel: true, ongoing: null, colorAlpha: null, colorRed: null, colorGreen: null, colorBlue: null, largeIcon: null, largeIconBitmapSource: null, onlyAlertOnce: null, showProgress: false, maxProgress: 0, progress: 0, indeterminate: false, enableLights: false, ledColorAlpha: null, ledColorRed: null, ledColorGreen: null, ledColorBlue: null, ledOnMs: null, ledOffMs: null, ticker: ticker}, payload: I'm the one} titlebodychannel id,这些都是我给的,但还有许多其他字段是channel NAME 。我猜这些会导致错误,但不确定。

在遵循文档时,我没有看到有关此类字段的任何说明。

某些线索将意味着巨大的帮助。非常感谢您的宝贵时间。

3 个答案:

答案 0 :(得分:2)

来自插件的readme

app_icon需要作为可绘制资源添加到Android主项目中

因此,将您的[{'Rank': 1, 'Company': 'Walmart', 'Country': 'United States', 'Industry': 'Retail', 'Revenue in USD': '$500 billion', 'rev per emp': 217391.30434782608}, {'Rank': 2, 'Company': 'State Grid', 'Country': 'China', 'Industry': 'Power', 'Revenue in USD': '$349 billion', 'rev per emp': 376142.84374767606}, {'Rank': 3, 'Company': 'Sinopec Group', 'Country': 'China', 'Industry': 'Petroleum', 'Revenue in USD': '$327 billion', 'rev per emp': 911953.2812190612}] 放入app_icon文件夹而不是drawable文件夹中,并将代码更改为:

mipmap

答案 1 :(得分:0)

我在这篇文章中找到了解决方案:

https://stackoverflow.com/a/60236675/11192570

使用以下代码:

  FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
          new FlutterLocalNotificationsPlugin();
      var androidPlatformChannelSpecifics = AndroidNotificationDetails(
          '1687497218170948721x8',
          'New Trips Notification ',
          'Notification Channel for vendor. All the new trips notifications will arrive here.',
          style: AndroidNotificationStyle.BigText,
          icon: "app_icon",
          styleInformation: BigTextStyleInformation(
            "hanji hogya?",//  'Locations: <b>${locations.replaceAll("\$", " to ")}</b><br>Vehicle: <b>$vehicle</b><br>Trip Type: <b>$tripType</b><br>Pick-Up Date: <b>$pickUpDate</b><br>Pick-Up Time: <b>$pickUpTime</b>',
              htmlFormatBigText: true,
              contentTitle: 'Amount:- <b>Rs 22000000</b>',
              htmlFormatContentTitle: true,
              summaryText: 'Trip Details',
              htmlFormatSummaryText: true));

答案 2 :(得分:0)

在安卓项目中。在文件夹“res”下,文件夹“mipmap/launcher_icon”中有一个图标,如图所示。 Folder structue

为了使用它,您可以设置AndroidNotificationDetails

library(boot)
library(survival)
data(aml, package = "boot") 

statMeanSurv <- function(data, var) {
  surv <- survfit(Surv(time, cens) ~ 1, data = data)
  mean(surv$surv) + var
}

res <- censboot(aml, statMeanSurv, R = 5,
                var = 1, parallel = "multicore", ncpus = 2)

res$t

所以只需设置图标:"mipmap/launcher_icon" 因为这是安卓资源名称。