Dart调用AndroidNotificationDetails报位置参数过多错误如何解决
问题根因
先看AndroidNotificationDetails的构造函数定义:
class AndroidNotificationDetails { /// Constructs an instance of [AndroidNotificationDetails]. const AndroidNotificationDetails( this.channelId, this.channelName, { // 剩余所有参数均为大括号包裹的命名参数 ... }) }
这个构造函数仅允许传入2个位置参数,分别是channelId(渠道ID)、channelName(渠道名称),从第三个参数开始,所有配置项都必须以参数名: 参数值的命名参数格式传入。
你触发的报错:
lib/Notification Manager/notification_manager.dart:12:42:
Error: Too many positional arguments: 2 allowed, but 3 found.
Try removing the extra positional arguments.
本质是调用构造函数时传了3个不带参数名的位置参数,第三个参数被Dart判定为非法的额外位置参数。
常见触发场景: 如果你是从老版本flutter_local_notifications插件升级上来的,老版本构造函数支持3个位置参数(第三个为渠道描述channelDescription),新版本把第三个及之后的所有参数都调整为命名参数,直接照搬老版本代码就会触发这个报错。
修复方法
找到notification_manager.dart第12行的AndroidNotificationDetails调用代码,把第三个及之后的所有参数都补上对应的参数名,转为命名参数传入即可。
- 错误写法示例(触发报错):
// 第三个参数直接传值,被识别为非法位置参数 AndroidNotificationDetails( 'default_channel', '默认通知渠道', '应用默认通知推送渠道', importance: Importance.high, priority: Priority.high, )
- 正确写法示例(修复后):
// 第三个及之后的参数都带上参数名,作为命名参数传入 AndroidNotificationDetails( 'default_channel', '默认通知渠道', channelDescription: '应用默认通知推送渠道', importance: Importance.high, priority: Priority.high, )
内容的提问来源于stack exchange,提问作者Tushar Mirche
相关产品推荐
相关产品推荐

