Flutter Dart:移除const后仍报非const构造函数调用错误的解决方法
解决Flutter中"The constructor being called isn't a const constructor"错误
问题根源
你的代码存在两个核心问题引发报错:
- const约束不匹配:最外层的
Column被标记为const,但它的子Widget(比如Expanded、内部嵌套的Container、Padding等)要么本身没有const构造,要么内部包含无法被const初始化的内容——const容器要求所有子元素必须是const构造的Widget,这直接触发了错误。 - 语法括号错误:
Expanded内部的Container结尾处多写了一个右括号,导致代码结构混乱,IDE的错误提示被进一步混淆。
修复步骤
- 移除外层
Column的const修饰符,因为它的子元素无法全部满足const构造要求。 - 修正多余的右括号,确保代码语法结构完整正确。
修正后的完整代码
class HomePage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( body: Container( padding: EdgeInsets.symmetric(vertical: 30), width: double.infinity, decoration: const BoxDecoration( gradient: LinearGradient( begin: Alignment.topCenter, colors: [ Color.fromARGB(255, 9, 106, 185), Color.fromARGB(255, 56, 145, 217), Color.fromARGB(255, 66, 161, 239), Color.fromARGB(255, 109, 179, 237) ] ) ), // 移除此处的const约束 child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ SizedBox(height: 80,), Padding( padding: EdgeInsets.all(20), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Text("Login", style: TextStyle(color: Colors.white, fontSize: 40),), SizedBox(height: 5,), Text("Welcome Back", style: TextStyle(color: Colors.white, fontSize: 18),) ], ), ), Expanded( child: Container( decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.only(topLeft: Radius.circular(50), topRight: Radius.circular(50)) ), child: Padding( padding: EdgeInsets.all(20), child: Column( children: <Widget>[ Container( decoration: BoxDecoration( boxShadow: [BoxShadow( color: Color.fromARGB(255, 5, 97, 173), blurRadius: 20, offset: Offset(0,10) )] ), ) ], ), ), ), ), ], ) ), ); } }
额外提示
- 只有当Widget的所有参数都是编译时常量,且自身支持const构造时,才能用const修饰。像
Expanded这类依赖父布局约束的Widget,本身没有const构造,不能放在const容器里。 - 若修复后IDE仍报错,可尝试重启IDE或执行
flutter clean清除缓存。
内容的提问来源于stack exchange,提问作者azuzu
相关产品推荐
相关产品推荐

