Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add Widget based on Condition

Tags:

flutter

dart

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?

like image 424
Blondy314 Avatar asked Feb 06 '19 17:02

Blondy314


People also ask

How to conditionally add widgets as children of a row?

So if we want to conditionally add widgets as children I usually do the following: Row ( children: <Widget> [ foo == 42 ? Text ("foo") : Container (), ], );

How to display widgets conditionally in flutter?

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

What is controlling widgets using conditional statements in mobile app development?

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.

How to apply conditional statement on widget tree?

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:


2 Answers

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.

like image 159
creativecreatorormaybenot Avatar answered Nov 11 '22 07:11

creativecreatorormaybenot


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 !!

like image 33
Ferdi Avatar answered Nov 11 '22 05:11

Ferdi