每次用户滚动ListView时获取滚动距离

时间:2019-07-16 10:24:58

标签: flutter

使用scrollListenerScrollController,如何获得用户每次滚动时从滚动开始到结束的滚动距离?

1 个答案:

答案 0 :(得分:1)

ScrollController有一个名为offset的属性,它将为您提供当前的偏移量。

下面是一个工作示例

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  ScrollController controller = ScrollController();
  double initialPosition = 0.0;
  double endPosition = 0.0;
  double distance = 0.0;

  @override
  void initState() {
    super.initState();

    controller = ScrollController();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: NotificationListener(
        onNotification: (notif) {
          if(notif is ScrollStartNotification) {
            initialPosition = controller.offset;
          } else if(notif is ScrollEndNotification) {
            endPosition = controller.offset;

            distance = endPosition - initialPosition;
            print(distance);
          }
          return true;
        },
        child: ListView(
        controller: controller,
        children: <Widget>[
          Container(
            height: 100.0,
            color: Colors.red,
          ),
          Container(
            height: 100.0,
            color: Colors.red,
          ),
          Container(
            height: 100.0,
            color: Colors.red,
          ),
          Container(
            height: 100.0,
            color: Colors.red,
          ),
          Container(
            height: 100.0,
            color: Colors.red,
          ),
          Container(
            height: 100.0,
            color: Colors.red,
          ),
          Container(
            height: 100.0,
            color: Colors.red,
          ),
          Container(
            height: 100.0,
            color: Colors.red,
          ),
          Container(
            height: 100.0,
            color: Colors.red,
          ),
        ],
      ),),
    );
  }
}

更新:添加了有助于检测开始和结束滚动的代码。