【问题标题】:Flutter AlwaysScrollableScrollPhysics() not workingFlutter AlwaysScrollableScrollPhysics()不起作用
【发布时间】:2020-03-11 03:08:14
【问题描述】:

问题

您好,我正在寻找一种解决方案,即使内容不足也允许用户在列表上滚动。 通过查看 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,
            ),
          );
        },
      ),
      
    );
  }
}

为什么这不起作用?

编辑

这是我期待的设计

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

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

【问题讨论】:

  • 您能否解释一下“即使内容不足也滚动列表”?您正在寻找的确切结果是什么?有没有可以展示的设计/gif?
  • 我编辑了帖子。希望我很清楚

标签: flutter


【解决方案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,您可以在此处查看更多信息:NotificationListener Class和ScrollNotification class

【讨论】:

  • 谢谢,这就是解决方案。添加通知监听器让我可以捕捉到任何事件。
猜你喜欢
  • 2022-11-14
  • 1970-01-01
  • 1970-01-01
  • 2020-02-06
  • 1970-01-01
  • 2021-05-17
  • 2021-11-18
  • 2018-09-17
  • 2021-02-13
相关资源
最近更新 更多