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

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

    In my app I created a WidgetChooser widget so I can choose between widgets without conditional logic:

    WidgetChooser(
          condition: true,
          trueChild: Text('This widget appears if the condition is true.'),
          falseChild: Text('This widget appears if the condition is false.'),
        );
    

    This is the source for the WidgetChooser widget:

    import 'package:flutter/widgets.dart';
    
    class WidgetChooser extends StatelessWidget {
      final bool condition;
      final Widget trueChild;
      final Widget falseChild;
    
      WidgetChooser({@required this.condition, @required this.trueChild, @required this.falseChild});
    
      @override
      Widget build(BuildContext context) {
        if (condition) {
          return trueChild;
        } else {
          return falseChild;
        }
      }
    }
    

提交回复
热议问题