How to use conditional statement within child attribute of a Flutter Widget (Center Widget)

前端 未结 18 2156
再見小時候
再見小時候 2020-11-30 18:50

So far whenever I needed to use a conditional statement within a Widget I have done the following (Using Center and Containers as simplified dummy examples):



        
18条回答
  •  情书的邮戳
    2020-11-30 19:51

    The other answers don't mention it, you may also:

    Use the Builder widget

    The Builder widget is meant for allowing the use of a closure when a child widget is required:

    A platonic widget that calls a closure to obtain its child widget.

    It is convenient anytime you need logic to build a widget, it avoids the need to create a dedicated function. Also i find it makes what's being done clearer compared to using an immediate anonymous function.

    You use the Builder widget as the child and provide your logic in its builder method. With your example it goes:

    Center(
      child: Builder(
        builder: (context) {
          if (condition) {
            return Container();
          } else {
            return Center();
          }
        }
      )
    )
    

    In such a trivial example the ternary operator would suffice (child: condition ? Container() : Center()), but if more logic is needed, the Builder provides a convenient place to hold it.

    Also I agree with other posters that the logic should be extracted from the UI code, but when it's only a switch or if/else statement used to determine the widget to build, I prefer to keep it there (provided the condition is simple, for example testing a value in a ViewModel). The Builder widget can help in this.

提交回复
热议问题