Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

flutter - How to check if scroll position is at top or bottom in ListView?

I'm trying to implement a infinite scroll functionality.

I tried using a ListView inside on a NotificationListener to detect scroll events, but I can't see an event that says if the scroll has reached the bottom of the view.

Which would be the best way to achieve this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There are generally two ways of doing it.

1. Using ScrollController

// Create a variable
var _controller = ScrollController(); 

@override
void initState() {
  super.initState();
  
  // Setup the listener.
  _controller.addListener(() {
    if (_controller.position.atEdge) {
      if (_controller.position.pixels == 0) {
        // You're at the top. 
      } else {
        // You're at the bottom. 
      }
    }
  });
}

Usage:

ListView(controller: _controller) // Assign the controller.

2. Using NotificationListener

NotificationListener<ScrollEndNotification>(
  onNotification: (scrollEnd) {
    var metrics = scrollEnd.metrics;
    if (metrics.atEdge) {
      if (metrics.pixels == 0) print('At top');
      else print('At bottom');
    }
    return true;
  },
  child: ListView.builder(
    physics: ClampingScrollPhysics(),
    itemBuilder: (_, i) => ListTile(title: Text('Item $i')),
    itemCount: 20,
  ),
)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...