https://api.flutter.dev/flutter/widgets/NotificationListener-class.html
예제)
NotificationListener<ScrollNotification>(
onNotification: (scrollNotification) {
if (scrollNotification is ScrollStartNotification) {
controller.pauseVideo();
} else if (scrollNotification is ScrollEndNotification) {
controller.playVideo();
}
return false;
},
child: SingleChildScrollView(
NotificationListener는 어떻게 동작하나?
Button(
onTap : (){
CustomNotification.dispatch(context)
}
이런식으로 커스텀 노티피케이션을 만들 수 있다. 그럼 Button의 상위의 NotificationLister 를 두면 그 노티피케이션을 받을 수 있다.
커스텀노티피케이션 클래스는 그 알림과 함께 보낼 정보들을 가진다.
예를들어 ScrollStartNotification은
ScrollMetrics이라는 스크롤 정보를 가진 객체를 가지고있다.
라이브러리 내부를 보자.
scroll_activity.dart
void dispatchScrollStartNotification(ScrollMetrics metrics, BuildContext? context) {
ScrollStartNotification(metrics: metrics, context: context).dispatch(context);
}
scroll_position.dart
void didStartScroll() {
activity!.dispatchScrollStartNotification(copyWith(), context.notificationContext);
}
이 didStartScroll를 적절한 시기에 불러서 NotificationListener에게 알린다.
void dispatch(BuildContext? target) {
// The `target` may be null if the subtree the notification is supposed to be
// dispatched in is in the process of being disposed.
target?.visitAncestorElements(visitAncestor);
}
bool visitAncestor(Element element) {
if (element is StatelessElement) {
final StatelessWidget widget = element.widget;
if (widget is NotificationListener<Notification>) {
if (widget._dispatch(this, element)) // that function checks the type dynamically
return false;
}
}
return true;
}
dispatch를 보면 조상을 방문하면서 NotificationListener를 찾는걸 볼 수 있다.
그리고 NotificationListener의 _dispatch를 부르면
final NotificationListenerCallback<T>? onNotification;
bool _dispatch(Notification notification, Element element) {
if (onNotification != null && notification is T) {
final bool result = onNotification!(notification);
return result == true; // so that null and false have the same effect
}
return false;
}
이렇게 NotificationListenr로 넘겨준 onNotification을 부른다.
'Flutter' 카테고리의 다른 글
Widget, Element, RenderObject (0) | 2021.09.04 |
---|---|
[플러터] 상태관리 라이브러리들의 동작원리 (0) | 2021.09.04 |