/
main_notification_listener.dart
80 lines (72 loc) · 2.14 KB
/
main_notification_listener.dart
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('NotificationListener')),
body: SafeArea(
child: NotificationListenerBuilder<ScrollNotification>(
cancel: true,
builder: (scroll, child) {
return Column(
children: <Widget>[
Container(
height: 50.0,
alignment: Alignment.center,
color: Colors.lightBlue.shade100,
child: Text((scroll?.metrics?.pixels ?? 0).toString()),
),
child,
],
);
},
child: Expanded(
child: Builder(
builder: (context) => ListView.builder(
itemBuilder: (_, index) {
return ListTile(
title: Text('Item $index'),
);
},
),
),
),
),
),
),
);
}
}
class NotificationListenerBuilder<T extends Notification>
extends StatefulWidget {
const NotificationListenerBuilder({
@required this.builder,
this.child,
this.cancel = false,
});
final Widget Function(T, Widget) builder;
final Widget child;
/// Whether to cancel the notification bubbling
final bool cancel;
@override
_NotificationListenerBuilderState createState() =>
_NotificationListenerBuilderState<T>(builder);
}
class _NotificationListenerBuilderState<T extends Notification>
extends State<NotificationListenerBuilder> {
_NotificationListenerBuilderState(this.builder);
Widget Function(T, Widget) builder;
T _notification;
@override
Widget build(BuildContext context) {
return NotificationListener<T>(
onNotification: (T notification) {
setState(() => _notification = notification);
return widget.cancel;
},
child: builder(_notification, widget.child),
);
}
}