Kdo*_*don 4 switch-statement dart flutter
我想在我的专栏中放置一个switch 语句来决定在我的FLUTTER 应用程序中构建哪些子组件组合。
在我的具体情况下,我创建了一个具有 4 种不同可能状态(AnimationEnum.None、AnimationEnum.etc)的枚举,每种状态都会触发不同的子级构建组合。
我可以通过在每个可能的小部件上方编写 if 语句来使其正常工作,但这显然是一种低效的做事方式,并且希望简化我的代码。
我觉得我已经很接近了,但还不能完全到达那里。这是带有占位符小部件的代码的简化版本:
谢谢!
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...
]
),
),
),
Run Code Online (Sandbox Code Playgroud)
这是不可能的,因为 dart 支持集合 if's(在集合本身内部)但不支持 switch。
最好的机会是提取逻辑并使用扩展运算符,如下所示。
@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;
}
}
Run Code Online (Sandbox Code Playgroud)
另外有关收集操作的更多信息请查看这篇文章
| 归档时间: |
|
| 查看次数: |
5943 次 |
| 最近记录: |