【 Flutter 】Flutter を 基礎 から 学習 ( ウィジェット編 ) part117 アニメーション系ウィジェット

基礎 から 学ぶ Flutter 」という書籍で  学習 したことを ブログでアウトプットしていこうと思います。今回は ウィジェット編 ( part117 )です。

前回

【 Flutter 】Flutter を 基礎 から 学習 ( ウィジェット編 ) part116 アニメーション系ウィジェット

引き続き、アニメーション系について学びます。

AnimatedControllerクラスを利用するウィジェット

アニメーションをつなげる

アニメーションをつなげるサンプルです。
ウィジェットがスムーズに入れ替わります。

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;

  // xxxTransitionウィジェットでは必須です。
  Animation<double>? _animation01;
  Animation<double>? _animation02;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      vsync: this,
      duration: const Duration(seconds: 3),
    );

    _animation01 = _controller!
        .drive(
          CurveTween(
            curve: Interval(
              0.0,
              0.6,
              curve: Curves.fastOutSlowIn,
            ),
          ),
        )
        .drive(
          Tween(
            begin: 1,
            end: 0,
          ),
        );

    _animation02 = _controller!
        .drive(
          CurveTween(
            curve: Interval(
              0.4,
              1.0,
            ),
          ),
        )
        .drive(
          Tween(
            begin: 0,
            end: 1,
          ),
        );
  }

  @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: _animation01!,
                child: Container(
                  width: 100.0,
                  height: 100.0,
                  color: Colors.green,
                ),
              ),
              FadeTransition(
                opacity: _animation02!,
                child: Container(
                  width: 100.0,
                  height: 100.0,
                  color: Colors.red,
                ),
              ),
            ],
          ),
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: () {
            _controller!.forward();
          },
          child: Icon(Icons.add),
        ),
      ),
    );
  }
}

最後に

Intervalの値がカギのようです。

今日はここまで!