gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 07:17:03 27 4
gpt4 key购买 nike

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

最佳答案

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

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

关于flutter - 每次用户滚动 ListView 时获取滚动距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57055162/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com