首页 > 解决方案 > 如何在 Flutter 中使用 Android 滚动行为为容器移动设置动画?

问题描述

我的目标是,有一个可以在垂直轴上拖动的容器。移开手指后,容器应该以我在结束触摸后的速度向前移动一点。在您停止在 Android 手机上滚动并且它会继续滚动更远一点后,我希望拥有完全相同的动画/感觉。

这是到目前为止的样子:

在此处输入图像描述

这是我的代码:

class _MyHomePageState extends State<MyHomePage>
    with SingleTickerProviderStateMixin {
  double _offeset = 0;

  double get offset => _offeset;

  set offset(double offeset) {
    if(offeset < 500)
    setState(() {
      _offeset = offeset;
    });
  }

  AnimationController controller;
  ClampingScrollSimulation simulation;

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

    controller = AnimationController(vsync: this, upperBound: 5)
      ..addListener(() {
        offset += controller.value;
      });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: <Widget>[
          Positioned(
            top: offset,
            left: 0,
            right: 0,
            child: GestureDetector(
              onVerticalDragUpdate: (DragUpdateDetails details) {
                offset += details.delta.dy;
              },
              onVerticalDragEnd: (DragEndDetails details) {
                simulation = ClampingScrollSimulation(
                   position: 0, velocity: details.primaryVelocity,
                );
                controller.animateWith(simulation);
              },
              child: Container(height: 50, width: 50, color: Colors.red),
            ),
          ),
        ],
      ),
    );
  }
}

问题是,这不是 Android 滚动动画,我不知道如何获得它。(感觉动画是线性的,过早停止,没有利用velocity参数)我什至在用这个ClampingScrollSimulation类,Flutter中所有的Scroll widgets都用这个类来模拟Android滚动。

标签: animationflutterdartwidget

解决方案


解决方案是将_controller.valuewith相乘_controller.velocity。像这样:

offset += controller.value * _controller.velocity / 100;

推荐阅读