只有记在脑海里的才是自己的,如果还没来得及,请写下来
flutter 条件判断-显示隐藏widget
2020-11-05 / 3 min read

flutter布局时,我们经常需要通过一些条件,去控制布局的样式,比如某个widget的显示与隐藏。
这里记录一下三种方式去实现,显示隐藏widget

1:利用 Offstage

一般我们在使用某个widget时,一定要要去看看官方的解释,Offstage的解释如下:

/// A widget that lays the child out as if it was in the tree, but without
/// painting anything, without making the child available for hit testing, and
/// without taking any room in the parent.
///
/// Offstage children are still active: they can receive focus and have keyboard
/// input directed to them.
///
/// Animations continue to run in offstage children, and therefore use battery
/// and CPU time, regardless of whether the animations end up being visible.
///
/// [Offstage] can be used to measure the dimensions of a widget without
/// bringing it on screen (yet). To hide a widget from view while it is not
/// needed, prefer removing the widget from the tree entirely rather than
/// keeping it alive in an [Offstage] subtree.
///
/// See also:
///
///  * [Visibility], which can hide a child more efficiently (albeit less
///    subtly).
///  * [TickerMode], which can be used to disable animations in a subtree.
///  * The [catalog of layout widgets](https://flutter.dev/widgets/layout/).
主要注意:
1:放一个子widget到 Offstage 下面,隐藏时不绘制子widget到屏幕上。
2:子widget隐藏时,不接收点击事件,不占用父节点的空间。
3:子widget虽然隐藏,但是可以接受焦点和键盘的信息,如果添加了动画,动画依然执行,需要手动停止动画(防止cup和电量消耗)

使用案例:offstagetrue 时 隐藏

Column(
    children: [
        Offstage(
        offstage: true,
        child: Container(
            height: 400,
            child: Text('22222'),
            decoration: BoxDecoration(
            color: Colors.yellow
            ),
        )
        ),
        Text('11111')
    ],
 )


使用案例:offstagefalse 时 显示

2:占位替换

用一个空的 widget与 需要显示隐藏的widget交互
使用方法:

Column(
    children: [
        false ? Container(
            height: 400,
            child: Text('22222'),
            decoration: BoxDecoration(
            color: Colors.yellow
            ),
        ) : Container(width: 0, height: 0),
        Text('11111')
    ],
)

此方法隐藏时,不占用位置

3:利用 Opacity

使用 Opacity 来控制其 子widget 的透明度,来实现显示隐藏

Column(
    children: [
        Opacity(
        opacity: 1,
        child:  Container(
            height: 400,
            child: Text('22222'),
            decoration: BoxDecoration(
            color: Colors.yellow
            ),
        )
        ),
        Text('11111')
    ],
 )


此方法隐藏时,会占用位置

总结:

1:使用 Offstage 控件 和 占位替换 的方式隐藏 widget 不占用父widget的空间位置

2:利用 Opacity 空间 隐藏 widget 会占用父widget的空间位置