Flutter : how to conditionally add a widget

删除回忆录丶 提交于 2021-02-08 07:48:29

问题


I want to add a text widget to the body if no data was return. Otherwise, I want to display the data. However, the following error is returned:

flutter: type '_CompactLinkedHashSet<Widget>' is not a subtype of type 'Widget'

My Code:

body: SafeArea(
  child: (isLoading)
    ? Center(
         child: new CircularProgressIndicator(),
      )
    : Stack(
         children: <Widget>[
            (jobDetail == null && !isLoading)
                ? noDataFound()
                : {
                     detailWidget(context, jobDetail),
                      applyWidget(context, jobDetail)
                  }
          ],
      ),
),

This is my code for the text widget

Widget noDataFound() {
    return Container(
      child: Center(
          child: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Text(
          "We could not get the detail. Please try again later",
          textAlign: TextAlign.center,
          style: TextStyle(fontSize: 20.0),
        ),
      )),
    );
  }

回答1:


You are trying to assign a hash set of widgets to the stack as the error message says (the {...} part makes it a hashset). The easiest way around that is changing the location of your ternary operator.

Example reduced to the core problem:

Stack(
  children: (jobDetail == null && !isLoading)
    ? [
        Container(),
      ]
    : [
        Container(),
        Container(),
      ],
),


来源:https://stackoverflow.com/questions/57075342/flutter-how-to-conditionally-add-a-widget

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!