flutter - 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...
]
),
),
),
解决方案
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
推荐阅读
- excel - 通过单击其中的单元格来显示列
- yocto - 在 yocto 战士分支中生成 core-image-selinux 时出现“介子失败”
- c# - IIS 条件未通过自定义操作正确传递
- javascript - 找到了 JQuery 元素,但它不可点击
- laravel - 如何解决队列工作人员在通过 queue:work 完成 3 个成功作业后自行停止和退出的问题
- uitapgesturerecognizer - 在 iOS 13 中向 PDFView 添加轻击手势识别器
- java - 调用MediaProjectionManager截图时,每次都会弹出截图权限框。如何设置取消?
- java - Hikari 连接池设置空闲连接但在 oracle Db 中有限制连接
- ruby-on-rails - 升级 Faraday gem:RuntimeError: Adapter 应该使用 `adapter` 方法设置,而不是 `use`
- javascript - 我想在我的 React Native 应用程序中的谷歌地图中显示附近的餐馆。当我调用 Google API 附近搜索时,它会抛出状态:'ZERO_RESULTS'