iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🙈

Toggling Visibility in Flutter: Using Visibility and AnimatedOpacity Widgets

に公開
2021/11/24
4件

TL;DR

Visibility Didn't Exist in the Past

It seems that the Visibility class was not provided in the early days.
Searching on Google brings up articles about implementing it yourself.
It appears to have become available around June 2019.

How to Use Visibility

It is very easy to use if you just want to simply toggle visibility.

To remove the space when hidden

// _visible = false; to hide
Visibility(
  visible: _visible,
  child: MyWidget(),
)

To keep reserving the space even when hidden

// _visible = false; to hide
Visibility(
  visible: _visible,
  maintainSize: true,
  child: MyWidget(),
)

Other properties are also available:

How to Use AnimatedOpacity

Use this if you want to fade in/out when showing/hiding.
Specify the transparency with opacity and the fade time with duration.
Since it only affects opacity, the space will be reserved after making it transparent.

// _visible = false; to hide
AnimatedOpacity(
  opacity: _visible ? 0.0 : 1.0,
  duration: Duration(milliseconds: 200),
  child: MyWidget(),
)

Since it only affects opacity, it would look unnatural to remove the space after making it transparent without an animation that collapses it.
It might be possible by using AnimatedSwitcher, wrapping it in an AnimatedContainer, and setting width or height to 0 according to _visible?
I haven't tried it yet, though.
→ Updated 2021/11/24
 I received a comment informing me that this can be done!

Discussion

wakewake

IgnorePointerを使うと簡単にAnimatedOpacityの領域も消せましたので他の方の参考にもなれば:)
https://stackoverflow.com/a/54607744

IgnorePointer(
  ignoring: !_visible,
  child: AnimatedOpacity(
    opacity: _visible ? 0.0 : 1.0,
    duration: Duration(milliseconds: 200),
    child: MyWidget(),
  ),
)
5
蓮美蓮美

AnimatedSwitcher を使って AnimatedContainer で包んでおいて
width や height を _visible に応じて 0 にしてやればできそう?

もう結論出てると思いますが、一応確認したところ出来ました。
ご報告までに。

1
北山淳也北山淳也

@蓮美 さん
ありがとうございます!追記しておきました🙇‍♂️