如何在Flutter中检测ListView的滚动位置

maj*_*i69 8 android dart flutter

我正在使用ListView小部件将项目显示为列表。在三个窗口中,查看项目必须将中间项目放置在中间。

那么,如何ListView在滚动停止时检测位置?

如何检测ListView滚动停止?

Peg*_*sis 22

majidfathi69 的回答很好,但您不需要在列表中添加控制器:(更改ScrollUpdateNotificationScrollEndNotification仅在滚动结束时收到通知时。)

NotificationListener<ScrollUpdateNotification>(
  child: ListView(
    children: ...
  ),
  onNotification: (notification) {
    //How many pixels scrolled from pervious frame
    print(notification.scrollDelta);

    //List scroll position
    print(notification.metrics.pixels);
  },
),
Run Code Online (Sandbox Code Playgroud)


maj*_*i69 14

我使用的NotificationListener是一个小部件,用于监听气泡冒泡的通知。然后使用ScrollEndNotification,它指示滚动已停止。

对于滚动位置,我使用的_scrollController类型是ScrollController

new NotificationListener(
  child: new ListView(
    controller: _scrollController,
    children: ...
  ),
  onNotification: (t) {
    if (t is ScrollEndNotification) {
      print(_scrollController.position.pixels);
    }
  },
),
Run Code Online (Sandbox Code Playgroud)

  • 对于 2021 年的用户,有一种更短的方法可以做到这一点(请参阅我的答案):) (2认同)

Sed*_*ush 11

您还可以通过以下步骤实现此功能

import 'package:flutter/material.dart';

class YourPage extends StatefulWidget {
  YourPage({Key key}) : super(key: key);

  @override
 _YourPageState createState() => _YourPageState();
}

class _YourPageState extends State<YourPage> {

  ScrollController _scrollController;
  double _scrollPosition;

 _scrollListener() {
  setState(() {
   _scrollPosition = _scrollController.position.pixels;
 });
}

@override
void initState() {
  _scrollController = ScrollController();
  _scrollController.addListener(_scrollListener);
  super.initState();
}

 @override
 Widget build(BuildContext context) {
  return Scaffold(
  appBar: AppBar(
    automaticallyImplyLeading: false,
    title: Text('Position $_scrollPosition pixels'),
  ),
  body: Container(
      child: ListView.builder(
    controller: _scrollController,
    itemCount: 200,
    itemBuilder: (context, index) {
      return ListTile(
        leading: Icon(Icons.mood),
        title: Text('Item: $index'),
      );
    },
  )),
);
}
}
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明


Oza*_*ver 6

如果你想检测你的滚动位置ListView,你可以简单地使用这个;

Scrollable.of(context).position.pixels


fzy*_*cjy 6

NotificationListener现在接受型参数,它使得代码短:)

NotificationListener<ScrollEndNotification>(
  child: ListView(
    controller: _scrollController,
    children: ...
  ),
  onNotification: (notification) {
    print(_scrollController.position.pixels);
    // Return true to cancel the notification bubbling. Return false (or null) to
    // allow the notification to continue to be dispatched to further ancestors.
    return true;
  },
),
Run Code Online (Sandbox Code Playgroud)

  • 使用“NotificationListener &lt;ScrollEndNotification&gt;”,我相信除了打印像素之外,您不再需要“_scrollController”。 (3认同)