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

Flutter中List首个元素无法显示问题求助(附代码)

错误原因排查
  • 语法错误:Text组件的字符串参数里同时写了"example text"和questions[0],但未用字符串拼接符+连接,不符合Dart语法规范。
  • const修饰冲突:外层的Expanded、Padding、Center都加了const修饰,但questions[0]是状态类中的非const成员,const Widget无法访问非const变量,会触发编译错误。
解决方案
  1. 移除不必要的const修饰(因为要访问状态类的成员变量,不能使用const Widget);
  2. 正确处理Text组件的字符串内容:要么直接使用questions[0],要么用+拼接需要的文本。

修正后的代码片段:

class _QuizPageState extends State<QuizPage> {
  List<Widget> scoreKeeper = [];

  // 顺便修正拼写错误:seacond → second
  List<String> questions = ["First ques", "second ques", "third ques"];
  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: <Widget>[
        Expanded( // 移除const
          flex: 5,
          child: Padding( // 移除const
            padding: EdgeInsets.all(10.0),
            child: Center( // 移除const
              child: Text( 
                questions[0], // 直接展示列表首个元素
                textAlign: TextAlign.center,
                style: TextStyle(
                  fontSize: 25.0,
                  color: Colors.white,
                ),
              ),
            ),
          ),
        ),
        // 其他组件代码...
      ],
    );
  }
}

如果需要保留"example text"并和问题内容拼接,修改Text的参数为:

Text( 
  "example text " + questions[0],
  textAlign: TextAlign.center,
  style: TextStyle(
    fontSize: 25.0,
    color: Colors.white,
  ),
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 14:46:00