Flutter AlwaysScrollableScrollPhysics()无法正常工作

时间:2019-11-15 01:19:10

标签: flutter

问题

您好,我正在寻找一种解决方案,即使内容不足,也允许用户在列表上滚动。 查看Flutter文档,我发现了此页面https://api.flutter.dev/flutter/widgets/ScrollView/physics.html

如文档所述

  

要强制滚动视图即使内容不足也始终可滚动(好像primary是true,但不必将其设置为true),请提供AlwaysScrollableScrollPhysics物理对象,如下所示:

physics: const AlwaysScrollableScrollPhysics(),

所以我尝试运行一个简单的代码,即使没有足够的内容,也可以检测用户滚动

代码

class Page extends StatefulWidget {
  @override
  _PageState createState() => _PageState();
}

class _PageState extends State<Page> {
  @override
  Widget build(BuildContext context) {

    final ScrollController scrollController = ScrollController();

    @override
    void initState(){
      scrollController.addListener((){
        print('listener called');
      });
      super.initState();
    }

    return Scaffold(
      body: ListView.builder(
        controller: scrollController,
        physics: const AlwaysScrollableScrollPhysics(),
        itemCount: 5,
        itemBuilder: (context, index){
          return Padding(
            padding: const EdgeInsets.only(bottom: 8.0),
            child: Container(
              color: Colors.black,
              height: 50,
            ),
          );
        },
      ),

    );
  }
}

为什么这不起作用?

编辑

这是我期待的设计

enter image description here

我有一个动态创建的列表。我希望即使没有滚动也可以检测到该列表上的用户垂直滑动,因为没有足够的元素来溢出屏幕高度。

在可滚动列表上,我可以简单地添加一个滚动侦听器,然后每次检测到滚动时,都可以使用scrollController.position info进行逻辑处理。 我希望即使用户在此类型的列表上滑动时也可以调用滚动侦听器

1 个答案:

答案 0 :(得分:1)

通过添加 AlwaysScrollableScrollPhysics ,我确实可以看到滚动效果,因此该部分似乎可以正常工作。也许将脚手架包装在 NotificationListener 上可以完成您想做的事情:

class _PageState extends State<Page> {
  @override
  Widget build(BuildContext context) {
    final ScrollController scrollController = ScrollController();

    return NotificationListener(
      child: Scaffold(
        body: ListView.builder(
          controller: scrollController,
          physics: const AlwaysScrollableScrollPhysics(),
          itemCount: 5,
          itemBuilder: (context, index) {
            return Padding(
              padding: const EdgeInsets.only(bottom: 8.0),
              child: Container(
                color: Colors.black,
                height: 50,
              ),
            );
          },
        ),
      ),
      onNotification: (scrollNotification) {
        if (scrollNotification is ScrollStartNotification) {
          print('Widget has started scrolling');
        }
        return true;
      },
    );
  }
}

NotificationListener 具有名为 onNotification 的属性,该属性可让您检查不同类型的 scrollNotifications ,您可以在此处进行更多检查:{{3 }}和NotificationListener Class