如何为通过滑动偏移旋转的小部件添加惯性? (增加动力)

How to add inertia to widget rotated by swipe offset? (add momentum)

例如,我有一个使用变量 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),
        ));
  }

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

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

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),
              ),
            );
          },
        ),
      ),
    );
  }
}