Flutter案例-点赞动画

效果:

按下缩小,松开恢复原状并变色

 

原理:

使用animation动画和三元运算

所有代码如下:

import 'package:flutter/material.dart';
import 'package:async/async.dart';
void main()=>runApp(MyApp());

class MyApp extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text("点赞动画"),
        ),
        body: LikeAnimationWidget(),
      ),
    );
  }
}
class LikeAnimationWidget extends StatefulWidget{
  @override
  _LikeAnimationWidgetState createState() {
    // TODO: implement createState
    return _LikeAnimationWidgetState();
  }
}
class _LikeAnimationWidgetState extends State with TickerProviderStateMixin{
  AnimationController controller;
  CurvedAnimation curve;
  Animation animationSize;
  double size=25.0;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    controller=AnimationController(vsync: this,duration: Duration(milliseconds: 150));
    curve=CurvedAnimation(parent: controller,curve: Curves.easeInCirc);
    animationSize=Tween(begin: 40.0,end: 35.0,).animate(controller);
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Center(
      child: LikeAnimation(
        controller: controller,
        list: [
          animationSize,
        ],
      ),
    );
  }
}

class LikeAnimation extends AnimatedWidget implements StatefulWidget{
  AnimationController controller;
  List list;
  bool color=false;
  LikeAnimation({
    this.controller, this.list
}):super(listenable:controller);

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return GestureDetector(
      child: Icon(
        Icons.favorite,
        size: list[0].value,
        color: color?Colors.red:Colors.grey,
      ),
        onTapDown: (DragDownDetails){
          controller.forward();
        },
        onTapUp: (DragDownDetails){
          if(!color){
            new Future.delayed(Duration(milliseconds: 100),(){
              controller.reverse();
              color=true;
            });
            return;
          }
          new Future.delayed(Duration(milliseconds: 100),(){
            controller.reverse();
            color=false;
          });
          return;
        },
    );
  }
}

 

你可能感兴趣的:(Flutter案例-点赞动画)