zl程序教程

您现在的位置是:首页 >  移动开发

当前栏目

Flutter TurnBox

2023-09-27 14:27:34 时间
class TurnBoxWidget extends StatefulWidget {
  const TurnBoxWidget({
    Key? key,
  }) : super(key: key);

  @override
  State<TurnBoxWidget> createState() {
    return TurnBoxRouteState();
  }
}

class TurnBoxRouteState extends State<TurnBoxWidget> {
  double _turns = .0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("TurnBox"),
      ),
      body: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            TurnBox(
                turns: _turns,
                speed: 500,
                child: const Icon(
                  Icons.refresh,
                  size: 50,
                )),
            TurnBox(
              turns: _turns,
              speed: 1000,
              child: const Icon(
                Icons.refresh,
                size: 100.0,
              ),
            ),
            ElevatedButton(
              child: const Text("顺时针旋转1/5圈"),
              onPressed: () {
                setState(() {
                  _turns += .2;
                });
              },
            ),
            ElevatedButton(
              child: const Text("逆时针旋转1/5圈"),
              onPressed: () {
                setState(() {
                  _turns -= .2;
                });
              },
            ),
          ],
        ),
      ),
    );
  }
}

class TurnBox extends StatefulWidget {
  const TurnBox(
      {Key? key,
      this.turns = 0, //旋转的“圈”数,一圈为360度,如0.25圈即90度
      this.speed = 200, //过渡动画执行的总时长
      required this.child})
      : super(key: key);

  final double turns;
  final int speed;
  final Widget child;

  @override
  State<TurnBox> createState() {
    return TurnBoxState();
  }
}

class TurnBoxState extends State<TurnBox> with SingleTickerProviderStateMixin {
  late AnimationController _controller;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
        vsync: this, lowerBound: -double.infinity, upperBound: double.infinity);
    _controller.value = widget.turns;
  }

  @override
  Widget build(BuildContext context) {
    return RotationTransition(
      turns: _controller,
      child: widget.child,
    );
  }

  @override
  void didUpdateWidget(TurnBox oldWidget) {
    super.didUpdateWidget(oldWidget);
    //旋转角度发生变化时执行过渡动画
    if (oldWidget.turns != widget.turns) {
      _controller.animateTo(
        widget.turns,
        duration: Duration(milliseconds: widget.speed),
        curve: Curves.easeOut,
      );
    }
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }
}
逆时针旋转默认顺时针旋转
在这里插入图片描述在这里插入图片描述在这里插入图片描述