Flutter中return语句三元运算符使用报错排查请求
我来帮你逐个拆解这些语法问题,其实都是Flutter Widget构造函数的使用规范和变量定义的小问题:
错误1:Column构造函数参数不匹配
? Column(Text("PAGE 1"))
^
packages/flutter/lib/src/widgets/basic.dart:4930:3: Context: Found this candidate, but the arguments don't match.
Column({
^^^^^^
Column的构造函数不接受单个Widget作为位置参数,它的子组件必须放在children这个命名参数的数组里。你直接把Text丢进去,Flutter找不到对应的构造函数,自然报错。
错误2:Center构造函数参数不匹配
/lib/components/challenge_menu.dart:32:17: Error: Too many positional arguments: 0 allowed, but 1 found.
Try removing the extra positional arguments.
: Center(
^
packages/flutter/lib/src/widgets/basic.dart:1984:9: Context: Found this candidate, but the arguments don't match.
const Center({ Key? key, double? widthFactor, double? heightFactor, Widget? child })
^^^^^^
Center的所有构造参数都是命名参数,你直接把Text("PAGE 2")作为位置参数传入是不允许的,必须通过child命名参数来指定它的子组件。
错误3:未定义的'id'变量
/lib/components/challenge_menu.dart:30:12: Error: The getter 'id' isn't defined for the class '_ChallengeMenuState'.
- '_ChallengeMenuState' is from 'package:osam2021/components/challenge_menu.dart' ('/lib/components/challenge_menu.dart').
Try correcting the name to the name of an existing getter, or defining a getter or field named 'id'.
return id == 0
^^
你的_ChallengeMenuState类里压根没定义id这个字段或者getter,代码里直接用肯定会报错。得先在类里声明这个变量,再根据业务需求初始化它。
修复后的完整代码示例
class _ChallengeMenuState extends State<ChallengeMenu> { // 先声明并初始化id变量,这里假设初始值为0,你可以根据实际需求修改 int id = 0; Widget _buildItems() { return id == 0 ? Column(children: const [Text("PAGE 1")]) : Center(child: const Text("PAGE 2")); } // 其他State类的代码... }
我还顺手给Text加了const修饰符,能帮着优化Widget性能,算是个小细节~
内容的提问来源于stack exchange,提问作者bobaguy0931

