简体   繁体   English

Flutter ListView、SliverList 等中的当前滚动偏移

[英]Current scroll offset inside a Flutter ListView, SliverList,etc

如何在 Flutter ListView, SliverList等中获取当前滚动偏移量?

  • If you're inside the scroll view use Scrollable.of(context).position.pixels . 如果您在滚动视图中,请使用Scrollable.of(context).position.pixels
  • If you're outside, you probably want to hand a ScrollController in as the controller argument of the scroll view, then you can read controller.offset . 如果你在外面,你可能想把ScrollController作为滚动视图的控制器参数,然后你可以读取controller.offset
  • Alternatively, use scroll notifications with NotificationListener . 或者,使用NotificationListener滚动通知。

This was asked on Flutter Gitter, and answered: https://gitter.im/flutter/flutter?at=591243f18a05641b1167be0e 这是在Flutter Gitter问的,并回答: https ://gitter.im/flutter/flutter?at = 591243f18a05641b1167be0e

For someone else, looking for code implementation, you can use ScrollController like this: 对于其他人,寻找代码实现,您可以像这样使用ScrollController

ScrollController _scrollController;

@override
void initState() {
  super.initState();
  _scrollController = ScrollController()
    ..addListener(() {
      print("offset = ${_scrollController.offset}");
  });
}

@override
Widget build(BuildContext context) {
  return ListView(
    controller: _scrollController, 
    children: <Widget>[],
  );
}

@override
void dispose() {
  _scrollController.dispose(); // it is a good practice to dispose the controller
  super.dispose();
}

Another approach is with NotificationListener另一种方法是使用NotificationListener

NotificationListener(
  child: ListView(
    controller: _scrollController,
    children: ...
  ),
  onNotification: (notification) {
    if (notification is ScrollEndNotification) {
      print(_scrollController.position.pixels);
    }
    return false;
  },
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM