一旦获得有关最大滚动范围的信息,我就会尝试显示一个小部件。如果我将 ScrollController
的实例分配给可滚动小部件的 controller
属性,我就可以找到该数字。
我的问题是 ScrollController
在构建期间附加到可滚动小部件,因此我无法在第一次构建之前使用最大滚动范围数。因此,我试图做的是在第一个构建中显示一个空的 Container
,然后用我真正想要的小部件切换那个空的 Container
。像这样:
_scrollController.positions.length == 0 ? new Container() : new Align(
alignment: Alignment.center,
child: new Container(
width: constraints.maxWidth,
height: 50.0,
color: Colors.black,
)
)
现在这当然不起作用,因为 _scrollController.positions.length
在开始时将为 0,并且当此值更改时(当 Controller 附上)。
所以我的问题是:有没有什么地方可以让我在 ScrollController
附加到可滚动小部件时得到通知?或者有更好的方法吗?
最佳答案
如果可滚动是widget.child
。
@override
Widget build(BuildContext context) {
return new NotificationListener<ScrollNotification>(
onNotification: _handleScrollNotification,
child: widget.child,
);
}
bool _handleScrollNotification(ScrollNotification notification) {
if (notification is ScrollUpdateNotification || notification is OverscrollNotification) {
widget.child.update(notification.metrics);
}
return false;
}
@override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) => afterFirstLayout(context));
}
void afterFirstLayout(BuildContext context) {
applyInitialScrollPosition();
}
void applyInitialScrollPosition() {
ScrollController scrollControler = widget.child.controller;
ScrollPosition position = scrollControler.position;
ScrollNotification notification = ScrollUpdateNotification(
metrics: FixedScrollMetrics(
minScrollExtent: position.minScrollExtent,
maxScrollExtent: position.maxScrollExtent,
pixels: position.pixels,
viewportDimension: position.viewportDimension,
axisDirection: position.axisDirection),
context: null,
scrollDelta: 0.0);
_handleScrollNotification(notification);
}
child 必须扩展 ChangeNotifier
并且有一个 update
方法:
void update(ScrollMetrics metrics) {
assert(metrics != null);
_lastMetrics = metrics; // Save the metrics.
notifyListeners();
}
所有这些只有在为可滚动对象(widget.child)明确定义了滚动 Controller 时才有效。
关于dart - 附加 ScrollController 时的事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49660921/