Flutter报错:无法将Null赋值给const构造函数的ValueListenable参数
问题解决:A value of type 'Null' can't be assigned to a parameter of type 'ValueListenable' in a const constructor
问题根源
报错核心是:你在const修饰的Scaffold、ValueListenableBuilder里,传入了非编译期常量的selectedIndexNotifier。selectedIndexNotifier是运行时初始化的ValueNotifier,不属于const常量,但const构造要求所有参数必须是编译时就能确定的常量,因此触发报错。
修复步骤
按以下方式修改代码即可解决:
- 移除
ScreenHome的build方法中,Scaffold、SafeArea、ValueListenableBuilder前的所有const关键字:
@override Widget build(BuildContext context) { return Scaffold( bottomNavigationBar: MMBottomNavigation(), body: SafeArea( child: ValueListenableBuilder( valueListenable: selectedIndexNotifier, builder: (BuildContext context, int updatedIndex, _) { return _pages[updatedIndex]; }, ), )); }
_pages列表可以保留const,因为内部的页面组件都是const构造的,不影响:
final _pages = const [ ScreenTransation(), ScreenCatagaries(), ];
- 其他位置的
const(比如MMBottomNavigation的构造、BottomNavigationBarItem的列表)可以正常保留,不会引发问题。
补充说明
如果之前移除const后问题仍存在,大概率是没有清理到Scaffold这类外层组件的const,或者是IDE分析缓存导致的。修改完成后,重启IDE的Dart分析服务,或热重载/重启应用即可生效。
内容的提问来源于stack exchange,提问作者Shuhaib
相关产品推荐
相关产品推荐

