LoginSignup
1
2

More than 1 year has passed since last update.

【Flutter】ローディングをVisibilityを使って実装する

Posted at

はじめに

最近Flutterで読み込み時のローディングを実装するときに個人的にとてもいいなと思うWidgetに出会ったので、簡単に使い方を紹介したいと思います。
  
今回使うのはVisibility Widgetです。

※今回の記事は、hooks_riverpod, state_notifierでの使用例を紹介しています。

使い方

こちらソースです。
見やすくなるよう、appBarとbodyは省略しています。

 @override
  Widget build(BuildContext context) {
    //boolで判断する
    final isLoading =
        useProvider(controllerProvider.select((value) => value.isLoading));
    //VisibilityをかぶせたいところをStackで囲む。
    return Stack(
      children: [
        Scaffold(
          appBar: _createAppBar(),
          body: Stack(
            children: [
              _createBody(),
              //ここ
              Visibility(
                visible: isLoading,
                child: Container(
                  color: Colors.white,
                  child: const Center(
                    child: CircularProgressIndicator(),
                  ),
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }

loadingを被せたいWidgetをStackで囲み、Visibilityを定義してあげる、といった感じです。

isLoadingの型はboolで初期値にfalseをもたせてます。

Visibilityvisibleに入れた値がtrueのときだけCircularProgressIndicator()が表示されます。

stateNotifier側では適宜ローディングを走らせたいタイミングで、

state = state.copyWith(isLoading: true)

として、ローディングを終わらせたいタイミングで、

state = state.copyWith(isLoading: false)

にすればあとはいい感じで画面にローディングが走ります。

  

以前までは三項演算子を使って実装していて、やってることに特に変わりはないですが、
専用のWidgetがあり、コードも若干見やすくなった気がします。

  

1
2
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
1
2