Skip to content

Commit c05a05e

Browse files
authored
1 parent 3e610f7 commit c05a05e

3 files changed

Lines changed: 175 additions & 0 deletions

File tree

Lines changed: 135 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,135 @@
1+
// Copyright 2014 The Flutter Authors. All rights reserved.
2+
// Use of this source code is governed by a BSD-style license that can be
3+
// found in the LICENSE file.
4+
5+
import 'package:flutter/material.dart';
6+
7+
/// Flutter code sample for [ScrollNotificationObserver].
8+
9+
void main() => runApp(const ScrollNotificationObserverApp());
10+
11+
class ScrollNotificationObserverApp extends StatelessWidget {
12+
const ScrollNotificationObserverApp({super.key});
13+
14+
@override
15+
Widget build(BuildContext context) {
16+
return MaterialApp(
17+
theme: ThemeData(useMaterial3: true),
18+
// The Scaffold widget contains a [ScrollNotificationObserver].
19+
// This is used by [AppBar] for its scrolled under behavior.
20+
//
21+
// We can use [ScrollNotificationObserver.maybeOf] to get the
22+
// state of this [ScrollNotificationObserver] from descendants
23+
// of the Scaffold widget.
24+
//
25+
// If you're not using a [Scaffold] widget, you can create a [ScrollNotificationObserver]
26+
// to notify its descendants of scroll notifications by adding it to the subtree.
27+
home: Scaffold(
28+
appBar: AppBar(
29+
title: const Text('ScrollNotificationObserver Sample'),
30+
),
31+
body: const ScrollNotificationObserverExample(),
32+
),
33+
);
34+
}
35+
}
36+
37+
class ScrollNotificationObserverExample extends StatefulWidget {
38+
const ScrollNotificationObserverExample({super.key});
39+
40+
@override
41+
State<ScrollNotificationObserverExample> createState() => _ScrollNotificationObserverExampleState();
42+
}
43+
44+
class _ScrollNotificationObserverExampleState extends State<ScrollNotificationObserverExample> {
45+
ScrollNotificationObserverState? _scrollNotificationObserver;
46+
ScrollController controller = ScrollController();
47+
bool _scrolledDown = false;
48+
49+
@override
50+
void didChangeDependencies() {
51+
super.didChangeDependencies();
52+
// Remove any previous listener.
53+
_scrollNotificationObserver?.removeListener(_handleScrollNotification);
54+
// Get the ScrollNotificationObserverState from the Scaffold widget.
55+
_scrollNotificationObserver = ScrollNotificationObserver.maybeOf(context);
56+
// Add a new listener.
57+
_scrollNotificationObserver?.addListener(_handleScrollNotification);
58+
}
59+
60+
@override
61+
void dispose() {
62+
if (_scrollNotificationObserver != null) {
63+
_scrollNotificationObserver!.removeListener(_handleScrollNotification);
64+
_scrollNotificationObserver = null;
65+
}
66+
controller.dispose();
67+
super.dispose();
68+
}
69+
70+
void _handleScrollNotification(ScrollNotification notification) {
71+
// Check if the notification is a scroll update notification and if the
72+
// `notification.depth` is 0. This way we only listen to the scroll
73+
// notifications from the closest scrollable, instead of those that may be nested.
74+
if (notification is ScrollUpdateNotification && defaultScrollNotificationPredicate(notification)) {
75+
final ScrollMetrics metrics = notification.metrics;
76+
// Check if the user scrolled down.
77+
if (_scrolledDown != metrics.extentBefore > 0) {
78+
setState(() {
79+
_scrolledDown = metrics.extentBefore > 0;
80+
});
81+
}
82+
}
83+
}
84+
85+
@override
86+
Widget build(BuildContext context) {
87+
return Stack(
88+
children: <Widget>[
89+
SampleList(controller: controller),
90+
// Show the button only if the user scrolled down.
91+
if (_scrolledDown)
92+
Positioned(
93+
right: 25,
94+
bottom: 20,
95+
child: Center(
96+
child: GestureDetector(
97+
onTap: () {
98+
// Scroll to the top when the user taps the button.
99+
controller.animateTo(0, duration: const Duration(milliseconds: 200), curve:Curves.fastOutSlowIn);
100+
},
101+
child: const Card(
102+
child: Padding(
103+
padding: EdgeInsets.all(8.0),
104+
child: Column(
105+
children: <Widget>[
106+
Icon(Icons.arrow_upward_rounded),
107+
Text('Scroll to top')
108+
],
109+
),
110+
),
111+
),
112+
),
113+
),
114+
),
115+
],
116+
);
117+
}
118+
}
119+
120+
class SampleList extends StatelessWidget {
121+
const SampleList({super.key, required this.controller});
122+
123+
final ScrollController controller;
124+
125+
@override
126+
Widget build(BuildContext context) {
127+
return ListView.builder(
128+
controller: controller,
129+
itemCount: 30,
130+
itemBuilder: (BuildContext context, int index) {
131+
return ListTile(title: Text('Item $index'));
132+
},
133+
);
134+
}
135+
}
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
// Copyright 2014 The Flutter Authors. All rights reserved.
2+
// Use of this source code is governed by a BSD-style license that can be
3+
// found in the LICENSE file.
4+
5+
import 'package:flutter/material.dart';
6+
import 'package:flutter_api_samples/widgets/scroll_notification_observer/scroll_notification_observer.0.dart' as example;
7+
import 'package:flutter_test/flutter_test.dart';
8+
9+
void main() {
10+
testWidgets('Scroll to top buttons appears when scrolling down', (WidgetTester tester) async {
11+
const String buttonText = 'Scroll to top';
12+
13+
await tester.pumpWidget(
14+
const example.ScrollNotificationObserverApp(),
15+
);
16+
17+
expect(find.byType(ScrollNotificationObserver), findsOneWidget);
18+
expect(find.text(buttonText), findsNothing);
19+
20+
// Scroll down.
21+
await tester.drag(find.byType(ListView), const Offset(0.0, -300.0));
22+
await tester.pumpAndSettle();
23+
24+
expect(find.text(buttonText), findsOneWidget);
25+
26+
await tester.tap(find.text(buttonText));
27+
await tester.pumpAndSettle();
28+
29+
expect(find.text(buttonText), findsNothing);
30+
});
31+
}

‎packages/flutter/lib/src/widgets/scroll_notification_observer.dart‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,15 @@ final class _ListenerEntry extends LinkedListEntry<_ListenerEntry> {
7171
/// This widget is similar to [NotificationListener]. It supports a listener
7272
/// list instead of just a single listener and its listeners run
7373
/// unconditionally, they do not require a gating boolean return value.
74+
///
75+
/// {@tool dartpad}
76+
/// This sample shows a "Scroll to top" button that uses [ScrollNotificationObserver]
77+
/// to listen for scroll notifications from [ListView]. The button is only visible
78+
/// when the user has scrolled down. When pressed, the button animates the scroll
79+
/// position of the [ListView] back to the top.
80+
///
81+
/// ** See code in examples/api/lib/widgets/scroll_notification_observer/scroll_notification_observer.0.dart **
82+
/// {@end-tool}
7483
class ScrollNotificationObserver extends StatefulWidget {
7584
/// Create a [ScrollNotificationObserver].
7685
///

0 commit comments

Comments
 (0)