首页 > 解决方案 > 如何为通过滑动偏移旋转的小部件添加惯性?(增加动力)

问题描述

例如,我有一个在用户滑动时使用变量旋转的小部件dragoffset += details.offset.dx

滑动结束时如何为旋转添加惯性?例如,当您松开手指时,对象继续以下降的速度旋转——就像 ListView 通常的行为一样。

以下是一些样板代码作为示例:

Widget rotatedWidget() {
    double fingerOffset = 0.0;
    return GestureDetector(
        onHorizontalDragUpdate: (details) {
          setState((){ 
             fingerOffset += details.delta.dx; 
          });
        },
        onHorizontalDragEnd: (details) {
           /// some code to add inertia
        },
        child: Transform.rotate(
          angle: offset,
          child: Container(width: 100, height: 100, color: Colors.blue),
        ));
  }

插图

标签: flutterflutter-animation

解决方案


感谢@pskink提供此解决方案。

(编辑:添加物理包导入和SingleTickerProviderStateMixin类的继承,因为 AnimationController 需要垂直同步到当前类)

import 'package:flutter/physics.dart';

class RotateState extends State<Rotate> with SingleTickerProviderStateMixin {

 AnimationController ctrl;

  @override
  void initState() {
    super.initState();
    ctrl = AnimationController.unbounded(vsync: this);
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onPanUpdate: (d) => ctrl.value += d.delta.dx / 100,
      onPanEnd: (d) {
        ctrl.animateWith(
          FrictionSimulation(
              0.05, // <- the bigger this value, the less friction is applied
              ctrl.value,
              d.velocity.pixelsPerSecond.dx / 100 // <- Velocity of inertia
          ));
        },
      child: Scaffold(
        appBar: AppBar(
          title: Text('RotatedBox'),
        ),
        body: AnimatedBuilder(
          animation: ctrl,
          builder: (ctx, w) {
            return Center(
              child: Transform.rotate(
                angle: ctrl.value,
                child: Container(width: 100, height: 100, color: Colors.blue),
              ),
            );
          },
        ),
      ),
    );
  }
}

在此处输入图像描述


推荐阅读