Current scroll offset inside a Flutter ListView, S

2019-02-22 12:25发布

问题:

How do I get the current scroll offset inside a Flutter ListView, SliverList, etc?

回答1:

  • If you're inside the scroll view use 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.
  • Alternatively, use scroll notifications with NotificationListener.

This was asked on Flutter Gitter, and answered: https://gitter.im/flutter/flutter?at=591243f18a05641b1167be0e



回答2:

For someone else, looking for code implementation, you can use ScrollController like this:

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


标签: dart flutter