Flutter 错误 元素类型 'List' 无法分配给列表类型 'Widget'

Flutter error The element type 'List' can't be assigned to the list type 'Widget'

我想像这段代码一样在 if 条件下显示两个 SizedBox。

  body: Center(
    child: Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        Flexible(
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: <Widget>[
              if (randomNumber == 1)[
              
                SizedBox(
                  child: TextButton(
                    child: Image.asset('images/test1.jpg'),
                  ),
                ),

                SizedBox(
                  child: TextButton(
                    child: Image.asset('images/test2.jpg'),
                  ),
                ),
            ]

if (randomNumber == 1)[ 行的 [ 处显示这样的错误。

The element type 'List<SizedBox>' can't be assigned to the list type 'Widget'.dart(list_element_type_not_assignable)

如何在if条件下使用两个sizebox?

只需将“if() []”更改为“if() {}”。 If else 语句必须使用花括号 ({})。不是 bracket/array[]

正确答案是,在 Widget 列表中,如果您想添加更多项目列表,您需要使用“...”运算符。在这种情况下它将是:

 Row(
    mainAxisAlignment: MainAxisAlignment.spaceAround,
    children: <Widget>[
      if (randomNumber == 1) ...[
          
        SizedBox(
          child: TextButton(
            child: Image.asset('images/test1.jpg'),
          ),
        ),

        SizedBox(
          child: TextButton(
            child: Image.asset('images/test2.jpg'),
          ),
        ),
    ],
)

您正在返回列表中的列表。在 if 语句中包含 [],删除它并使用 {} 代替。