Flutter:如何有条件地添加小部件 [英] Flutter : how to conditionally add a widget

查看:63
本文介绍了Flutter:如何有条件地添加小部件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果没有返回任何数据,我想在正文中添加一个文本小部件.否则,我想显示数据.但是,返回以下错误:

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'

我的代码:

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.

示例归结为核心问题:

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

这篇关于Flutter:如何有条件地添加小部件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆