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

前端 未结 18 2107
再見小時候
再見小時候 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: [
         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: [
            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: [
            ConditionalSwitch.single(
              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) instead of a single one. Use Conditional.list() and ConditionalSwitch.list()!

提交回复
热议问题