我必须归档:一个包含我的应用程序代码,另一个包含一个小部件。该小部件的构造函数将 SingleChildScrollView
类型的子组件作为参数。小部件获取孩子的 ScrollController
并为其附加一个侦听器。问题是听众……不听。它不检测任何状态。我怎样才能让它听听变化?
这是我的代码:
app.dart - 包含我的应用代码的文件
import 'package:flutter/material.dart';
import 'MyWidget.dart';
class MyTestPage2 extends StatelessWidget {
const MyTestPage2({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: MyWidget(
child: SingleChildScrollView(
scrollDirection: Axis.horizontal,
physics:
BouncingScrollPhysics(parent: AlwaysScrollableScrollPhysics()),
controller: ScrollController(),
child: Text(
'1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30',
style: TextStyle(fontSize: 30),
maxLines: 1,
),
)),
),
);
}
}
MyWidget.dart - 带有问题小部件的文件
import 'package:flutter/material.dart';
class MyWidget extends StatefulWidget {
final SingleChildScrollView child;
final ScrollController scrollController;
MyWidget({
Key? key,
required this.child,
}) : assert(child.controller != null,
'You need to provide a ScrollController to the child'),
scrollController = child.controller!,
super(key: key);
@override
_MyWidget createState() => _MyWidget();
}
class _MyWidget extends State<MyWidget> {
@override
void initState() {
widget.scrollController.addListener(_onScroll);
super.initState();
}
void _onScroll() {
final offset = widget.scrollController.offset;
final minOffset = widget.scrollController.position.minScrollExtent;
final maxOffset = widget.scrollController.position.maxScrollExtent;
final isOutOfRange = widget.scrollController.position
.outOfRange;
final hasReachedTheEnd = offset >= maxOffset && !isOutOfRange;
final hasReachedTheStart = offset <= minOffset && !isOutOfRange;
final isScrolling = maxOffset > offset && minOffset < offset;
// This code doesn't print anything.
if (isScrolling) {
print('isScrolling');
} else if (hasReachedTheStart) {
print('hasReachedTheStart');
} else if (hasReachedTheEnd) {
print('hasReachedTheEnd');
} else {
print('IDK');
}
}
@override
void dispose() {
widget.scrollController.removeListener(_onScroll);
widget.scrollController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return widget.child;
}
}
答案 0 :(得分:1)
根据在模拟器上的测试,侦听器似乎可以正常工作,并且正在将日志消息写入滚动事件。我建议尝试完全重新启动应用程序或重新安装它,如果您将小部件用作其他小部件的子部件,您也可以修改小部件树。
-