I want to add a MaterialButton
in a widget's build
method only if some condition is true. For instance:
if (..) {
MaterialButton(..)
}
How do I achieve this in Flutter?
So if we want to conditionally add widgets as children I usually do the following: Row ( children: <Widget> [ foo == 42 ? Text ("foo") : Container (), ], );
Flutter provides various ways to display Widgets conditionally and in this article, we are going to implement all the methods. Method 1: Using If condition. This is flutter’s way to display a widget if the condition is true. Syntax: if (condition) Widget()
There are so much conditions in mobile application development where developer wants to control which widget he wants to display on certain condition. These type of functionality is called as Controlling widgets using conditional statements.
Text("A is greater than 10"), ]else...[ Text("A is less than or Equal to 10") ] ]) You can apply this method of conditional statement on widget tree which has "children" property, for example, Column (), Row (), Wrap () widgets. Method 3: Apply Conditions (IF... ELSE) on LayoutBuilder:
It is very simple using conditional operators:
build(context) => condition ? MaterialButton(...) : Container();
In this case, condition
is a boolean expression (returning bool
, same thing you would put into an if-statement) and the empty Container
will render as empty space and will not take up any space.
Yes actually I see at least two ways of doing it.
The first one is :
Container(
child: your_test_here ? MaterialButton() : Container(height:0), //or any other widget but not null
)
The other way of doing it is by creating a function:
Widget your_test_widget(){
if (your_test_here){
return MaterialButton();
}
else{
return Container(height:0); //or any other widget but not null
}
}
Call it in your tree :
Container(
child:your_test_widget(),
)
Hope it helps !!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With