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

flutter conditionally show widget
flutter conditional statement
conditional icon flutter
flutter for loop inside widget
children: <widget
flutter conditionally include widget
flutter include widget
dart if else

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

new Center(
  child: condition == true ? new Container() : new Container()
)

Though when I tried using an if/else statement it would lead to an Dead code warning:

new Center(
  child: 
    if(condition == true){
      new Container();
    }else{
      new Container();
    }
)

Interestingly enough I tried with a switch case statement and it gives me the same warning and thus I cannot run the code. Am I doing something wrong or is it so that one cannot use if/else or switch statements without flutter thinking there is dead code?

In Dart, if/else and switch are statements not expressions. They don't return a value so you can't pass them to constructor params. If you have a lot of conditional logic in your build method, then it is a good practice to try and simplify it. For example, you can move self-contained logic to methods, and use if/else statements to initialize local variables which you can later use.

Using a method and if/else
Widget _buildChild() {
  if (condition) {
    return ...
  }
  return ...
}

Widget build(BuildContext context) {
  return new Container(child: _buildChild());
}
Using an if/else
Widget build(BuildContext context) {
  Widget child;
  if (condition) {
    child = ...
  } else {
    child = ...
  }
  return new Container(child: child);
}

Flutter state management using Provider, So far whenever I needed to use a conditional statement within a Widget I have done the following (Using Center and Containers as simplified  Flutter Use Conditional Statement in Child Widget Container Center 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.

Actually you can use if/else and switch and any other statement inline in dart / flutter.

Use an immediate anonymous function
class StatmentExample extends StatelessWidget {
  Widget build(BuildContext context) {
    return Text((() {
      if(true){
        return "tis true";}

      return "anything but true";
    })());
  }
}

ie wrap your statements in a function

(() {
  // your code here
}())

I would heavily recommend against putting too much logic directly with your UI 'markup' but I found that type inference in Dart needs a little bit of work so it can be sometimes useful in scenarios like that.

Use the ternary operator
condition? Text("True"): null,
Use If or For statements or spread operators in collections
children: [
  ...manyItems,
  oneItem,
  if(canIKickIt)
    ...kickTheCan
  for (item in items)
    Text(item)
Use a method
child: getWidget()

Widget getWidget() {
  if (x > 5) ...
  //more logic here and return a Widget
Redefine switch statement

As another alternative to the ternary operator, you could create a function version of the switch statement such as in the following post https://stackoverflow.com/a/57390589/1058292.

  child: case2(myInput,
  {
    1: Text("Its one"),
    2: Text("Its two"),
  }, Text("Default"));

Flutter Use Conditional Statement in Child Widget Container Center pass the widget name in any child attribute of Container, Center, Row,  How to use conditional statement within child attribute of a Flutter Widget (Center Widget) 0 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):

I found out that an easy way to use conditional logic to build Flutter UI is to keep the logic outside of the UI. Here is a function to return two different colors:

Color getColor(int selector) {
  if (selector % 2 == 0) {
    return Colors.blue;
  } else {
    return Colors.blueGrey;
  }
}

The function is used below to to set the background of the CircleAvatar.

new ListView.builder(
  itemCount: users.length,
  itemBuilder: (BuildContext context, int index) {
    return new Column(
      children: <Widget>[
        new ListTile(
          leading: new CircleAvatar(
            backgroundColor: getColor(index),
            child: new Text(users[index].name[0])
          ),
          title: new Text(users[index].login),
          subtitle: new Text(users[index].name),
        ),
        new Divider(height: 2.0),
      ],
    );
  },
);

Very neat as you can reuse your color selector function in several widgets.

It is okay for a single Text widget, but the readability quickly become very bad when the child widget is multi-layered. In Flutter you can do conditional rendering: Those logic/statements are often related to the condition only, encapsulating them into a builder function makes the code cleaner, and  How to use conditional statement within child attribute of a Flutter Widget (Center Widget) dart flutter 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):

For the record, Dart 2.3 added the ability to use if/else statements in Collection literals. This is now done the following way:

return Column(children: <Widget>[
  Text("hello"),
  if (condition)
     Text("should not render if false"),
  Text("world")
],);

Flutter Issue #28181 - Inline conditional rendering in list

is mostly syntax sugar for InheritedWidget, to make common use-cases straightforward. Let's walk through most popular 'Counter Widget': Notion of Widget. In Flutter, almost everything is a Widget. Think of a Widget as a visual component (or a component that interacts with the visual aspect of an application). When you need to build anything that directly or indirectly is in relation with the layout, you are using Widgets. Notion of Widgets tree. Widgets are organized in tree

Here is the solution. I have fixed it. Here is the code

child: _status(data[index]["status"]),

Widget _status(status) {
  if (status == "3") {
    return Text('Process');
  } else if(status == "1") {
    return Text('Order');
  } else {
    return Text("Waiting");
  }
}

I often find myself optionally wanting a child in a column component. For example Option 2: ternary operator using an empty widget when the optional child should not be shown. Widget flutter/packages/flutter/lib/src/widgets/framework.​dart. Line 595 Inline conditional rendering in list #28181. Closed. 54 How to use conditional statement within child attribute of a Flutter Widget (Center Widget) 26 What is the Dart null checking idiom or best practice? 24 knockoutjs - bindings with parameters triggered on load

Synchronous conditional widget renderer. Flutter Android iOS web Using this you can avoid implicit conditional statements in your code to show/hide a children: <Widget>[ Icon(Icons.edit), ConditionalBuilder( condition:  59 How to use conditional statement within child attribute of a Flutter Widget (Center Widget) 30 What is the Dart null checking idiom or best practice? 24 knockoutjs - bindings with parameters triggered on load

In this example, the widget tree consists of two widgets, the Center widget and You can then use the Positioned widget on children of a Stack to position them  children: < Widget >[ new MyCellWidget(0), new MyCellWidget(1),] But I have to make it dynamic with function as values will change in future, above code is just prototype. Flutter examples are very few.

What happens when you call setState() from a stateful widget in flutter? 2018 · With the AnimatedContainer widget, you just build it once with a particular attribute Flutter Use Conditional Statement in Child Widget Container widget, Center  62 How to use conditional statement within child attribute of a Flutter Widget (Center Widget) 30 What is the Dart null checking idiom or best practice? 24 knockoutjs - bindings with parameters triggered on load

Comments
  • If you want to insert a block where widgets should be instantiated you probably better build your widget in class methods
  • In my opinion, this is the most complete answer, thanks @orangesherbert
  • I like your answer, Thanks
  • Just a note if anyone gets stuck, if you are using Provider to rebuild your widgets on global state change, and you are getting data via "Provider.of", your conditional statement may not be re-evaluated until some other action rebuilds your widget. You need to be getting your conditional variable via "Consumer" that is being returned to the Widget build function, then your conditional statement should be properly re-evaluated as global state changes.
  • I tried this and worked for me the exact way. Thanks
  • I have dart 2.5 but I get error running above code. It says ` this code is required to be compatible with earlier versions. try updating SDK constraints`
  • emmm, interesting~
  • Do they add for loop feature? if so how to implement it?
  • @Aseem dart.dev/tools/diagnostic-messages#sdk_version_ui_as_code
  • How to using it
  • condition? Text("True"): null, this does an error Asertion false in console, on runtime execution
  • @exequielc you must add .where(notNull).toList() and the end of the WidgetList and the method bool notNull(Object o) => o != null;. Try whole example...
  • As of Dart 2.3 to conditionally include a widget in a list you can use: [Text("Hello"), if(world) Text("World")]