运行时如何创建Dart常量列表适配Flutter本地通知Actions?
解决flutter_local_notifications运行时生成AndroidNotificationActions的问题
问题根源
- 用
const List声明的列表是不可修改的常量列表,调用add()方法自然会触发Unsupported operation: Cannot add to an unmodifiable list错误。 - 如果你试图在
const AndroidNotificationDetails的构造中传入非const列表,会触发编译错误——因为const构造要求所有参数必须是编译期就能确定的常量,而someRunTimeData这类运行时数据根本无法满足这个要求。
正确实现代码
放弃const修饰AndroidNotificationDetails,同时用final创建可动态修改的actions列表:
// 用final声明可修改的空列表,不需要加const final List<AndroidNotificationAction> androidActions = []; // 运行时动态添加带可变数据的action androidActions.add(AndroidNotificationAction("action1", someRunTimeData)); // 按需添加更多动态生成的action androidActions.add(AndroidNotificationAction("action2", anotherRuntimeValue)); // 创建AndroidNotificationDetails实例时不要加const,直接传入动态列表 AndroidNotificationDetails( 'your channel id', 'your channel name', actions: androidActions, // 其他配置参数... );
补充说明
如果你的场景特殊到必须使用const构造(这种情况极少),那根本没办法传入运行时数据——因为const构造的所有参数必须在编译阶段确定。这种情况下只能放弃const,使用普通构造实例化AndroidNotificationDetails,这也是处理动态数据的标准做法。
内容的提问来源于stack exchange,提问作者pinoyyid
相关产品推荐
相关产品推荐

