Flutter学习之路->摇晃小动画

223 阅读1分钟

这是一个摇晃小动画

import 'dart:math';

import 'package:flutter/material.dart';

class ShakeAnimation extends StatefulWidget {


  @override
  _ShakeAnimationState createState() => _ShakeAnimationState();
}

class _ShakeAnimationState extends State<ShakeAnimation>
    with TickerProviderStateMixin {
  late AnimationController _controller;
  late Animation<double> _animation;

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

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

    _animation = Tween<double>(
      begin: -1.0,
      end: 1.0,
    ).animate(
      CurvedAnimation(
        parent: _controller,
        curve: Curves.linear,
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return AnimatedBuilder(
      animation: _animation,
      child: Center(child: Container(width:100,height:100,color:Colors.blue)),
      builder: (BuildContext context, Widget? child) {
        return Transform.rotate(
          angle: _animation.value * pi / 90.0,
          child: child,
        );
      },
    );
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }
}