颤振:使ListView在底部反弹,并在顶部位置夹紧

时间:2019-10-19 14:58:39

标签: flutter flutter-layout

我想将两种ScrollPhysics应用于我的ListView。当用户到达列表的底部时,我希望发生BouncingScrollPhysics(),但是当用户到达列表的顶部时,它不应该弹跳而是执行ClampingScrollPhysics()。如何实现呢?

1 个答案:

答案 0 :(得分:2)

截屏:

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")),
    ),
  );
}