Current scroll offset inside a Flutter ListView, SliverList,etc

后端 未结 2 924
悲&欢浪女
悲&欢浪女 2021-01-04 06:46

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

相关标签:
2条回答
  • 2021-01-04 06:59

    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();
    }
    
    0 讨论(0)
  • 2021-01-04 07:01
    • 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

    0 讨论(0)
提交回复
热议问题