1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

flutter_hooksでプログレスバーをアニメーションする

Last updated at Posted at 2021-09-18

背景

プログレスバーを無限にループさせる方法は非常に簡単ですが、flutter_hooksでプログレスバーを【時間】で推移させるアニメーション方法はWeb上でも記載少ないのでまとめました。
flutter_hooksには、デフォルトでuseAnimationのフックを備えているので今回はそちらを利用しています。

実装イメージ

output.gif
※注: GIF的に無限ループしていますが、実装上は一回きりのアニメーション処理となっています

プラグイン環境

flutter_hooks: ^0.18.0

準備

プラグインをインストールするために、pubspec.yamlのdependenciesにflutter_hooksを追加

dependencies:
  flutter:
    sdk: flutter

  cupertino_icons: ^1.0.2
  flutter_hooks: ^0.18.0  # ←✨追加✨

実装

以下のflutter_hooksプラグインの公式[1]とこちらのQiita記事[2]を参考にして実装しました。
[1] https://pub.dev/documentation/flutter_hooks/latest/flutter_hooks/useAnimation.html
[2] https://qiita.com/toda-axiaworks/items/f1f7acf9a636f52c67b3

もし、以下ソースコードを簡単に動かしたい場合は、GitHubに置いたので参考にしていただければと。

class HooksProgressBar extends HookWidget {
  const HooksProgressBar({Key key, @required this.progressTime})
      : super(key: key);

  final Duration progressTime;

  @override
  Widget build(BuildContext context) {
    /// forwardは1回きり。repeatで繰り返しの表現となりますが、プログレスバーなので1回で良いかなと。
    final controller = useAnimationController(
      duration: progressTime,
    )..forward();

    /// AnimatedBuilderを使うことがポイント✨✨これがないとアニメーションしない。
    return AnimatedBuilder(
      animation: controller,
      builder: (context, _) {
        return LinearProgressIndicator(
          value: controller.value,

          /// 色を変更したい場合も念のため、記載しておきます。微妙にハマったので。
          valueColor: AlwaysStoppedAnimation<Color>(Colors.orange),
        );
      },
    );
  }
}

参考のため、呼び出し元も記載しておきます。

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Hooks ProgressBar',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text('Hooks ProgressBar'),
        ),
        body: Center(
          /// アニメーションに掛ける時間として、Durationクラスを渡す。仮で5秒を設定。
          child: HooksProgressBar(
            progressTime: Duration(seconds: 5),
          ),
        ),
      ),
    );
  }
}
1
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?