Blog スタッフブログ

Flutter システム開発 ひとくちコードスニペット

[Flutter]ロード中にインジケータを表示するコードスニペット

こんにちは、株式会社MIXシステム開発担当のBloomです。

今回はFlutterで利用できるコードスニペットを紹介します。まずはWidgetクラスを一つ定義しましょう。

import 'package:flutter/material.dart';
class LoadingIndicator extends StatelessWidget {
  const LoadingIndicator({
    Key? key,
  }) : super(key: key);


  @override
  Widget build(BuildContext context) {
    return const ColoredBox(
        color: Colors.transparent,
        child: Center(
          child: CircularProgressIndicator(),
        ),
      );
  }

}

これは全画面を覆う形で表示され、画面中央に標準のCircularProgressIndicatorを表示するインジケータ表示用クラスです。Colors.transparentの部分を書き換えることで背景色を変更することができます。

早速組み込んでみましょう。


class MyPage extends StatefulWidget {
  const MyPage({super.key});

  @override
  State< MyPage > createState() => _MyPage();
}

class _MyPage extends State<MyPage> {
  bool isLoading = false;

  void anyLoading() async {
    setState(() {
      isLoading = true;
    });
    try {
      // 本来はここで例外が出るような通信処理を記述します
      await Future.delayed(const Duration(seconds: 3));
    } catch (e) {
      debugPrint(e.toString());
    } finally {
      setState(() {
        isLoading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return PopScope(
        canPop: false,
        child: Stack(
          children: [buildBody(), if (isLoading) LoadingIndicator()],
        ));
  }

  Widget buildBody() {
    return Scaffold(/* ここに画面の中身を記述しましょう */);
  }
}

このような構造で指定することで、isLoadingがtrueの間だけインジケータを表示することができます。良かったですね。


Warning: Undefined array key 0 in /home/fl0uhem6u4/mixltd.jp/public_html/cms/wp-content/themes/mix_theme/pagination-single.php on line 3

Warning: Attempt to read property "cat_ID" on null in /home/fl0uhem6u4/mixltd.jp/public_html/cms/wp-content/themes/mix_theme/pagination-single.php on line 3