Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 231
Zhangir Siranov Avatar asked Oct 19 '19 14:10

Zhangir Siranov


1 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")),
    ),
  );
}
like image 63
CopsOnRoad Avatar answered Oct 21 '22 01:10

CopsOnRoad