You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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构造要求所有参数必须是编译时就能确定的常量,因此触发报错。

修复步骤

按以下方式修改代码即可解决:

  1. 移除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];
          },
        ),
      ));
}
  1. _pages列表可以保留const,因为内部的页面组件都是const构造的,不影响:
final _pages = const [
  ScreenTransation(),
  ScreenCatagaries(),
];
  1. 其他位置的const(比如MMBottomNavigation的构造、BottomNavigationBarItem的列表)可以正常保留,不会引发问题。

补充说明

如果之前移除const后问题仍存在,大概率是没有清理到Scaffold这类外层组件的const,或者是IDE分析缓存导致的。修改完成后,重启IDE的Dart分析服务,或热重载/重启应用即可生效。

内容的提问来源于stack exchange,提问作者Shuhaib

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 18:13:11