有没有办法在水平滚动视图中将抖动动画化为特定的偏移量?

时间:2019-08-29 14:16:28

标签: listview flutter flutter-layout

在用户停止滚动后,我试图为列表视图中的特定点设置动画。但是以某种方式,当我在_controller.animateTo(<parameters>)中使用NotificationLister<ScrollEndNotification>时,它不起作用。但是,当我使用ScrollUpdateNotification时它确实起作用,但是在这种情况下,这是没有用的。

Positioned(
          right: 15,
          top: 80,
          width: 180,
          height: 40,
          child: Container(
            decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.all(Radius.circular(20))),
            child: NotificationListener<ScrollEndNotification>(
              onNotification: (ScrollEndNotification sn){
                _controller.animateTo(60, duration: Duration(milliseconds: 500), curve: Curves.linear);
                return true;
              },
              child: ListView.builder(
                scrollDirection: Axis.horizontal,
                itemCount: currencies.length,
                itemBuilder: ((BuildContext ctxt, int index){
                  return Container(width: 60.0, child: Text(currencies[index].symbol, style: TextStyle(color: Theme.of(context).primaryColor, fontSize: 20),), alignment: Alignment.center);
                }),
                controller: _controller,
              ),
            )
          )
        ),

简而言之:用户停止滚动后,我需要为ScrollView的偏移量设置动画

1 个答案:

答案 0 :(得分:1)

在您的代码中:

更改-_controller.animateTo(60, duration: Duration(milliseconds: 500), curve: Curves.linear);

_controller.animateTo(_controller.offset + 60, duration: Duration(milliseconds: 500), curve: Curves.linear);

更新 -我们需要添加几毫秒的延迟才能使其正常工作。

工作代码:

@override
  Widget build(BuildContext context) {
    return Scaffold(
      //  backgroundColor: Color.fromARGB(255, 22, 22, 22),
      body: NotificationListener<ScrollEndNotification>(
        onNotification: (ScrollEndNotification sn) {
          print(scrollViewColtroller.position.userScrollDirection);
          Future.delayed(Duration(milliseconds: 500), () {
            if (scrollViewColtroller.offset != 60.0) {
              scrollViewColtroller.animateTo(100,
              duration: Duration(milliseconds: 500), curve: Curves.linear);
        }
          });
          return true;
        },
        child: ListView.builder(
          itemBuilder: (context, i) {
            return Padding(
              padding: const EdgeInsets.all(8.0),
              child: Container(
                  width: 50.0,
                  color: (i % 2) == 0 ? Colors.green : Colors.red,
                  child: Center(
                      child: Text(
                    i.toString(),
                    style: TextStyle(fontSize: 18.0, color: Colors.white),
                  ))),
            );
          },
          shrinkWrap: true,
          controller: scrollViewColtroller,
          scrollDirection: Axis.horizontal,
        ),
      ),
    );
  }

输出:每次滚动时,我们都会在用户滚动结束后动画回到容器2。

enter image description here