flutter 中如何显示条件 widget
1. 场景:
在 flutter 日常开发中经常会遇见这样的需求,如: 只有用户是 vip 时,才能展示某个入口或者某个模块。这样的需求在开发业务需求中多如牛毛,那你是如何来优雅的实现的呢?
2. 推荐实现方式
下面是本人在开发中常用的集中实现方式,博友们可以根据自己的业务需求可以参考。
if 形式
这是一种非常常见的形式,满足条件就实现 widget。示例如下:
column( mainaxisalignment: mainaxisalignment.center, children: <widget>[ const text( 'you have pushed the button this many times:', ), text( '$_counter', style: theme.of(context).texttheme.headlinemedium, ), if (_counter > 2) container( width: 100, height: 100, color: colors.red, ) ], ),
注意: 在 if 后面不能使用大括号 ({})。 错误指示如下:
if-else 形式
这也是一种常见的形式,满足条件显示 widget1 ;不满足条件显示 widget2 。示例如下:
column( mainaxisalignment: mainaxisalignment.center, children: <widget>[ const text( 'you have pushed the button this many times:', ), text( '$_counter', style: theme.of(context).texttheme.headlinemedium, ), if (_counter > 2) container( width: 100, height: 100, color: colors.red, ) else container( width: 100, height: 100, color: colors.green, ) ], )
注意: 在 if-else 后面不能使用大括号 ({}); if 下的组件件的后面不能使用逗号(,)。 错误写法示例:
if...[widget1,widget2] 形式
该种形式也是常用于业务开发,它是当条件成立时,显示多个 widget。 示例如下:
column( mainaxisalignment: mainaxisalignment.center, children: <widget>[ const text( 'you have pushed the button this many times:', ), text( '$_counter', style: theme.of(context).texttheme.headlinemedium, ), if (_counter > 2) ...[ container( width: 100, height: 100, color: colors.red, ), container( width: 100, height: 100, color: colors.green, ) ], ], )
if...[widget1,widget2] else...[widget3,widget4] 形式
该种形式也是常用于业务开发,它是当条件成立时,显示多个 widget;条件不成立时,显示多个 widget。 示例如下:
column( mainaxisalignment: mainaxisalignment.center, children: <widget>[ const text( 'you have pushed the button this many times:', ), text( '$_counter', style: theme.of(context).texttheme.headlinemedium, ), if (_counter > 2) ...[ container( width: 100, height: 100, color: colors.red, ), container( width: 100, height: 100, color: colors.green, ) ] else ...[ container( width: 100, height: 100, color: colors.pinkaccent, ), container( width: 100, height: 100, color: colors.yellow, ), ] ], )
注意: if 下的组件集合的后面不能使用逗号(,)。 错误写法示例:
函数形式
这种形式是将这一块的逻辑抽离到另一个地方。该方法有个不足之处,那就是在不满足条件时也要返回一个 widget。 示例如下:
column( mainaxisalignment: mainaxisalignment.center, children: <widget>[ const text( 'you have pushed the button this many times:', ), text( '$_counter', style: theme.of(context).texttheme.headlinemedium, ), getwidget1(), ], ) // 函数形式 widget getwidget1() { if (_counter > 2) { return container( width: 100, height: 100, color: colors.green, ); } else { return container( width: 100, height: 100, color: colors.pinkaccent, ); } } }
3. 总结
以上就是 flutter 如何显示条件 widget 的方式。其实还有其他的方法,例如 switch 。这些其他的方法我们在后续文章中介绍。
以上就是flutter中显示条件widget的实现方式的详细内容,更多关于flutter显示widget的资料请关注代码网其它相关文章!
发表评论