Flutter学习之路->跳动小动画

78 阅读1分钟

这是一个跳动的动画

import 'dart:async';
import 'package:flutter/material.dart';

class JumpAnimationWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("跳动动画示例"),
      ),
      body: Center(
        child: JumpingAnimation(),
      ),
    );
  }
}

class JumpingAnimation extends StatefulWidget {
  @override
  _JumpingAnimationState createState() => _JumpingAnimationState();
}

class _JumpingAnimationState extends State<JumpingAnimation> with TickerProviderStateMixin {
  late AnimationController _jumpingController;
  late Animation<double> _jumpingAnimation;

  @override
  void initState() {
    super.initState();

    _jumpingController = AnimationController(
      vsync: this,
      duration: Duration(milliseconds: 1500),
    )..repeat(reverse: true);

    _jumpingAnimation = Tween(
      begin: 0.0,
      end: 30.0,
    ).animate(CurvedAnimation(
      parent: _jumpingController,
      curve: Curves.easeOutQuad,
    ));

    _jumpingController.addListener(() {
      setState(() {});
    });
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        if (_jumpingController.isDismissed) {
          _jumpingController.forward();
          Future.delayed(Duration(milliseconds: 400)).then((_) {
            _jumpingController.reverse();
          });
        }
      },
      child: Transform.translate(
        offset: Offset(0.0, -_jumpingAnimation.value),
        child: Container(
          width: 30.0,
          height: 30.0,
          decoration: BoxDecoration(
            color: Colors.red,
            borderRadius: BorderRadius.circular(15.0),
          ),
        ),
      ),
    );
  }

  @override
  void dispose() {
    _jumpingController.dispose();
    super.dispose();
  }
}
```
```