简体   繁体   中英

Flutter : how to conditionally add a widget

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),
        ),
      )),
    );
  }

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(),
      ],
),

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM