【 Flutter 】Flutter を 基礎 から 学習 ( ウィジェット編 ) part118 アニメーション系ウィジェット
「 基礎 から 学ぶ Flutter 」という書籍で 学習 したことを ブログでアウトプットしていこうと思います。今回は ウィジェット編 ( part118 )です。
前回
【 Flutter 】Flutter を 基礎 から 学習 ( ウィジェット編 ) part117 アニメーション系ウィジェット
引き続き、アニメーション系について学びます。
カスタムアニメーション
オリジナルのアニメーションを実装したい場合、AnimatedWidget
を継承するかAnimatedBuilder
ウィジェットを使えます。
どちらのウィジェットを使用するにしてもAnimationController
クラスを使います。
AnimatedWidgetの場合
AnimatedWidget
を使用する場合、buld()
メソッドが何度も呼び出されるので実装には注意が必要です。
解決方法としてはフィールドでキャッシュ(クラス変数とするということ?)やconst生成などがあるようです。
import 'package:flutter/material.dart';
void main() {
runApp(new MaterialApp(home: new MyHomePage()));
}
class MyHomePage extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return _MyHomePageState();
}
}
class _MyHomePageState extends State<MyHomePage>
with SingleTickerProviderStateMixin {
AnimationController? _controller;
Animation<double>? _animation;
@override
void initState() {
super.initState();
_controller = AnimationController(
vsync: this,
duration: const Duration(seconds: 3),
);
_animation = _controller!.drive(
Tween(begin: 0, end: 300),
);
}
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'テスト中!',
theme: ThemeData(primarySwatch: Colors.blue),
debugShowCheckedModeBanner: false,
home: Scaffold(
body: Center(
child: Stack(
children: <Widget>[
FadeTransition(
opacity: _animation!,
child: AnimatedLogo(
key: null,
animation: _animation,
),
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
_controller!.forward();
},
child: Icon(Icons.add),
),
),
);
}
}
class AnimatedLogo extends AnimatedWidget {
AnimatedLogo({
Key? key,
Animation<double>? animation,
}) : super(key: key, listenable: animation!);
Animation<double> get animation => listenable as Animation<double>;
@override
Widget build(BuildContext context) {
// 本書では以下のように実装してありますがどうにも動作しません・・・。
// final Animation<double> animation = listenable;
return Center(
child: Container(
height: animation.value, width: animation.value,
// 何度も呼ばれる
child: const FlutterLogo(),
),
);
}
}
Flutterのロゴが迫ってくる感じにアニメーションします!
最後に
よく考えてみればメソッド内にfinalというのは少し変化も(変じゃないかも)しれません。
今日はここまで!
参考
AnimatedWidget class – widgets library – Dart API (flutter.dev)
ディスカッション
コメント一覧
まだ、コメントがありません