首页 > 解决方案 > How can I implement a switch statement inside a Column widget? FLUTTER

问题描述

I would like to put a switch statement inside of my Column to decide what mix of children widgets to buildin my FLUTTER APP.

In my specific case I have created an enum with 4 different possible states (AnimationEnum.None, AnimationEnum.etc), each triggering a different build mix of children.

I can get this working fine by writing an if statement above EVERY possible widget, but that is clearly an inefficient way of doing things, and want to streamline my code.

I feel like I am close but cant quite get there. Here is a simplified version of the code with placeholder widgets:

thanks!

              child: Container(
                  
                    child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        crossAxisAlignment: CrossAxisAlignment.stretch,
                        children: [

                        switch(widget._cardAnimType)

                  case AnimationEnum.None: {
                  Widget1('args'),
                  Widget2('args'),
                  Widget3('args'),
                  //etc
                  break;
                  }
                    case AnimationEnum._card1Correct: {
                  Widget1('args'),
                  Widget2('args'),
                  Widget3('args'),
                  //etc
                  break;
                  }
                    ///more switch statements here...
                    ]
                  ),
              ),
            ),

标签: flutterdartswitch-statement

解决方案


It's not possible as dart supports collections if's(inside the collection itself) but not switch.

Your best chance at it is extracting the logic and using a spread operator like follows.

  @override
  Widget build(BuildContext context) {
    return Column(children: [...extractedMethod(widget._cardAnimType)],);
  }


List<Widget> (AnimationEnum animation){
                        switch(animation)

                  case AnimationEnum.None: {
                  Widget1('args'),
                  Widget2('args'),
                  Widget3('args'),
                  //etc
                  break;
                  }
                    case AnimationEnum._card1Correct: {
                  Widget1('args'),
                  Widget2('args'),
                  Widget3('args'),
                  //etc
                  break;
                  }
}


Also for more info on collection operation check out this article


推荐阅读