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

前端 未结 18 1973
再見小時候
再見小時候 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:36

    In flutter if you want to do conditional rendering, you may do this:

    Column(
       children: <Widget>[
         if (isCondition == true)
            Text('The condition is true'),
       ],
     );
    

    But what if you want to use a tertiary (if-else) condition? when the child widget is multi-layered.

    You can use this for its solution flutter_conditional_rendering a flutter package which enhances conditional rendering, supports if-else and switch conditions.

    If-Else condition:

    Column(
          children: <Widget>[
            Conditional.single(
              context: context,
              conditionBuilder: (BuildContext context) => someCondition == true,
              widgetBuilder: (BuildContext context) => Text('The condition is true!'),
              fallbackBuilder: (BuildContext context) => Text('The condition is false!'),
            ),
          ],
        );
    

    Switch condition:

    Column(
          children: <Widget>[
            ConditionalSwitch.single<String>(
              context: context,
              valueBuilder: (BuildContext context) => 'A',
              caseBuilders: {
                'A': (BuildContext context) => Text('The value is A!'),
                'B': (BuildContext context) => Text('The value is B!'),
              },
              fallbackBuilder: (BuildContext context) => Text('None of the cases matched!'),
            ),
          ],
        );
    

    If you want to conditionally render a list of widgets (List<Widget>) instead of a single one. Use Conditional.list() and ConditionalSwitch.list()!

    0 讨论(0)
  • 2020-11-30 19:37

    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

    0 讨论(0)
  • 2020-11-30 19:38

    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"));
    
    0 讨论(0)
  • 2020-11-30 19:39

    I personally use if/else statement in children with this kind of block statement. It only supports on Dart version 2.3.0 above.

    if / else

    Column(
        children: [
            if (_selectedIndex == 0) ...[
              DayScreen(),
            ] else ...[
              StatsScreen(),
            ],
        ],
     ),
    

    if / else if

    Column(
        children: [
            if (_selectedIndex == 0) ...[
              DayScreen(),
            ] else if(_selectedIndex == 1)...[
              StatsScreen(),
            ],
        ],
     ),
    
    0 讨论(0)
  • 2020-11-30 19:41

    This is great article and conversation. I tried to use the ternary operator as described. But the code didn't work resulting in an error as mentioned.

    Column(children: [ condition? Text("True"): null,],);
    

    The ternary example above is miss leading. Dart will respond with an error that a null was returned instead of widget. You can't return null. The correct way will be to return a widget:

    Column(children: [ condition? Text("True"): Text("false"),],); 
    

    In order for the ternary to work you need to return a Widget. If you don't want to return anything you can return a empty container.

    Column(children: [ condition? Text("True"): Container(),],); 
    

    Good luck.

    0 讨论(0)
  • 2020-11-30 19:42

    ****You can also use conditions by using this method** **

     int _moneyCounter = 0;
      void _rainMoney(){
        setState(() {
          _moneyCounter +=  100;
        });
      }
    
    new Expanded(
              child: new Center(
                child: new Text('\$$_moneyCounter', 
    
                style:new TextStyle(
                  color: _moneyCounter > 1000 ? Colors.blue : Colors.amberAccent,
                  fontSize: 47,
                  fontWeight: FontWeight.w800
                )
    
                ),
              ) 
            ),
    
    0 讨论(0)
提交回复
热议问题