Flutter: Make ListView bounce at the bottom and clamp at the top position

Viewed 4910

There are two types of ScrollPhysics that I want to apply to my ListView. When user reaches the bottom of the List, I want BouncingScrollPhysics() to take place, but when user reaches the top, it shouldn't bounce but rather perform ClampingScrollPhysics(). How to achieve this?

2 Answers

Screenshot:

enter image description here


// create 2 instance variables
var _controller = ScrollController();
ScrollPhysics _physics = ClampingScrollPhysics();

@override
void initState() {
  super.initState();
  _controller.addListener(() {
    if (_controller.position.pixels <= 56)
      setState(() => _physics = ClampingScrollPhysics());
    else
      setState(() => _physics = BouncingScrollPhysics());
  });
}

@override
Widget build(BuildContext context) {
  return Scaffold(
    body: ListView.builder(
      controller: _controller,
      physics: _physics,
      itemCount: 20,
      itemBuilder: (_, i) => ListTile(title: Text("Item $i")),
    ),
  );
}

I don't wont to reload every time it change the scroll position. And I hit upon a good one. so I leave it for future readers!

    _controller.addListener(() {
      if (_controller.position.pixels < 0) _controller.jumpTo(0);
    });
Related