Flutter Icons交错动画

发布时间 2023-12-25 15:30:13作者: angelwgh
import 'package:flutter/material.dart';

class AnimateIcons extends StatelessWidget {
  const AnimateIcons({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Icons动画'),
      ),
      body: const AnimateIconsContent(),
    );
  }
}

class MyAnimationIcon extends AnimatedWidget {
  const MyAnimationIcon({super.key, required Animation<double> animation})
      : super(listenable: animation);
  // 设置 动画显示的时间,
  static final _opacityTween = Tween<double>(begin: 0, end: 1)
      .chain(CurveTween(curve: const Interval(0.3, 1.0)));
  static final _opacityTween1 = Tween<double>(begin: 1, end: 0)
      .chain(CurveTween(curve: const Interval(0, 0.8)));
  @override
  Widget build(BuildContext context) {
    final animation = listenable as Animation<double>;
    return Container(
      child: Stack(children: [
        ScaleTransition(
          scale: _opacityTween.animate(animation),
          child: Icon(Icons.menu),
        ),
        ScaleTransition(
          scale: _opacityTween1.animate(animation),
          child: Icon(Icons.close),
        )
        // ScaleTransition(scale: animation)
      ]),
    );
  }
}

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

  @override
  State<AnimateIconsContent> createState() => _AnimateIconsContentState();
}

class _AnimateIconsContentState extends State<AnimateIconsContent>
    with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  String iconState = '';

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _controller = AnimationController(
      duration: const Duration(seconds: 1),
      vsync: this,
    )..addStatusListener((status) {
        setState(() {
          iconState = status.toString();
        });
      });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(children: [
          AnimatedIcon(
            icon: AnimatedIcons.close_menu,
            progress: _controller,
          ),
          MyAnimationIcon(
            animation: _controller,
          ),
          const SizedBox(
            height: 20,
          ),
          SizedBox(
            child: Text(iconState),
          )
        ]),
      ),
      floatingActionButton: FloatingActionButton(onPressed: () {
        if (iconState == 'AnimationStatus.completed') {
          _controller.reverse();
        } else if (iconState == 'AnimationStatus.dismissed' ||
            iconState == '') {
          _controller.forward();
        }
      }),
    );
  }
}