LoginSignup
2
3

More than 3 years have passed since last update.

Flutterでボタンとかテキストを隠す方法

Posted at

FlutterでボタンとかのHideってどうやるの?

最近、趣味でFlutterを使ってアプリ開発をやるようになって、ふとボタンやテキストを隠したくなった時に「そもそもFlutterではどうやってWidgetを隠すんだ?」と思ったので、そのまとめ(+備忘録)です。

結論: 「Visibility Widget」で対象のウィジェットをラップする

解決方法はめっちゃ簡単で「Visiblity」というウィジェットで隠したいウィジェット(ボタンとかテキストとか)をラップするだけ

Visibility(
  child: Text('隠れるよ'),
  visible: false, // ここで隠すか表示するかを選択する
)

ね?簡単でしょ?

Flutterの公式をみてみると

By default, the visible property controls whether the child is included in the subtree or not; when it is not visible, the replacement child (typically a zero-sized box) is included instead.

要するに、visibleプロパティーがfalse(=表示しない)の場合はchildに設定されているウィジェットの代わりに高さゼロのSizedBoxが設定されるらしい。

実例

実際にどうやってvisibleを制御するのかを、Flutterのデフォルトのサンプルを改良して「カウントが10以上になると、新たにTextウィジェットが追加される機能」を実装してみる。

main.dart
class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  // 追加
  bool _isVisible = false;

  void _incrementCounter() {
    setState(() {
      _counter++;
      // 追加
      _isVisible = (_counter >= 10);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.display1,
            ),
            // 追加
            Visibility(
              child: Text('Count is 10 or more'),
              visible: _isVisible,
            )
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

変更点をひとつづつみていくと、、、

  // 追加
  bool _isVisible = false;

ここでは、新たに追加するウィジェットを表示するかどうかの変数を新たに定義している。

  void _incrementCounter() {
    setState(() {
      _counter++;
      // 追加
      _isVisible = (_counter >= 10);
    });
  }

ここでは、_incrementCounter()が呼び出されるたび(プラスボタンが押されるたび)に_counterが10以上でないかをチェックして値を反映している。

// 追加
Visibility(
  child: Text('Count is 10 or more'),
  visible: _isVisible,
)

ここでは、新たにカウントが10以上になったときに表示するウィジェットをツリーに追加している。
またvisible: _isVisibleの部分でここでウィジェットの表示・非表示を設定している。

終わりに

宣言的UIのフレームワークを今まであまり使ったことがなかったので、ボタンとかを隠すときに「どうやんねんこれ?」って思ったんですが、意外に簡単にできたので「やっぱりFlutterは使いやすいなぁ」と安い感想を思い浮かべました。

最近、Flutterを使ったアプリ開発がかなり楽しいので引き続き頑張って学習していこうと思います(英語も...)

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3