根据条件添加小部件

Blo*_*314 6 dart flutter

我只想MaterialButtonbuild某些条件成立时添加一个小部件的方法.例如:

if (..) {
    MaterialButton(..)
}
Run Code Online (Sandbox Code Playgroud)

我如何在Flutter中实现这一目标?

cre*_*not 7

使用条件运算符非常简单:

build(context) => condition ? MaterialButton(...) : Container();
Run Code Online (Sandbox Code Playgroud)

在这种情况下,condition是一个布尔表达式(返回bool,与您将放入 if 语句中的内容相同)并且空Container将呈现为空空间并且不会占用任何空间。


Fer*_*rdi 5

是的,实际上我看到至少有两种方法可以做到。

第一个是:

Container(
  child: your_test_here ? MaterialButton() : Container(height:0), //or any other widget but not null
)
Run Code Online (Sandbox Code Playgroud)

另一种方法是创建一个函数:

Widget your_test_widget(){
  if (your_test_here){
    return MaterialButton();
  }
  else{
    return Container(height:0); //or any other widget but not null
  }
}
Run Code Online (Sandbox Code Playgroud)

在你的树中调用它:

Container(
  child:your_test_widget(),
)
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你 !!


Rob*_*eda 1

这是一个很好的问题!

假设您想在容器中添加按钮,您可以执行以下操作:

Container (
    child: MyWidget()
)


Widget MyWidget() {
    if (...) {
        return new MaterialButton(
            ...
        )
    }

    return Container();
}
Run Code Online (Sandbox Code Playgroud)

显然这里添加 Container 是一个例子,你可以为每个子元素分配一个返回 Widget 的方法!

一个更解释性的例子:

class Example extends StatefulWidget {

  // code

  @override
  EventPageState createState() => ExampleState();
}

class ExampleState extends State<Example> {
  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        children: <Widget>[
          Text("Static Widget")
          CustomDynamicWidget(),
        ],
      ),
    )
  }

  Widget CustomDynamicWidget() {
    if (...) {
      return new Text("Dynamic Widget IF block")      
    } else if (...) {
      return new Text("Dynamic Widget ELSE IF block")
    }

    return Container();
  }

}
Run Code Online (Sandbox Code Playgroud)