Visitar URL original
Send statusBarTouch events via dedicated messages (#179643) · chunhtai/packages@e6b568a · GitHub
Skip to content

Commit e6b568a

Browse files
Send statusBarTouch events via dedicated messages (#179643)
Instead of using fake touch events. Before this patch `FlutterViewController` sends two fake touch events (down and up), at `(0, 0)` to the framework to signal that the status bar is tapped on iOS. The scaffold widget and the cupertino page scaffold widget set up gesture detectors to listen for these fake taps, and scroll the "primary" scrollable container to the top in response. This messaging mechanism is sometimes ambiguous, as the framework may interpret that as a pair of regular pointer tap events (for instance in #177992 the modal barrier claims the tap gesture and as a result the modal barrier is dismissed by the fake touch events). This PR changes that to communicate the status bar tap event via a new system channel, and dispatch the events via `WidgetsBindingObserver`s in the framework. See also flutter/flutter#177992 (comment) Fixes #177992, fixes #175606 It appears that UIKit also has access to the coordinates of the touch events to determine which scrollable view(s?) to dispatch the scroll to top event to. ```objc * frame #0: 0x00000001032f6520 UIPlayground.debug.dylib`MyScrollViewController.scrollViewShouldScrollToTop(scrollView=0x0000000106014800) at UIScrollView.swift:13:3 frame flutter#2: 0x00000001867c9300 UIKitCore`-[UIScrollView _scrollToTopIfPossible:] + 316 frame flutter#3: 0x00000001867c9604 UIKitCore`-[UIScrollView _scrollToTopFromTouchAtScreenLocation:resultHandler:] + 40 frame flutter#4: 0x0000000186299bbc UIKitCore`__71-[UIWindow _scrollToTopViewsUnderScreenPointIfNecessary:resultHandler:]_block_invoke.358 + 168 frame flutter#5: 0x000000018629981c UIKitCore`-[UIWindow _scrollToTopViewsUnderScreenPointIfNecessary:resultHandler:] + 1212 frame flutter#6: 0x000000018581ed8c UIKitCore`-[UIStatusBarManager _handleScrollToTopAtXPosition:] + 192 frame flutter#7: 0x000000018581eb60 UIKitCore`-[UIStatusBarManager handleTapAction:] + 60 ``` Unfortunately that information is not available to user application. The iOS accessibility bridge currently does create dummy UIScrollViews for each scrollable in the accessibility tree so may be we can take advantage of that in the future. ## Pre-launch Checklist - [ ] I read the [Contributor Guide] and followed the process outlined there for submitting PRs. - [ ] I read the [Tree Hygiene] wiki page, which explains my responsibilities. - [ ] I read and followed the [Flutter Style Guide], including [Features we expect every widget to implement]. - [ ] I signed the [CLA]. - [ ] I listed at least one issue that this PR fixes in the description above. - [ ] I updated/added relevant documentation (doc comments with `///`). - [ ] I added new tests to check the change I am making, or this PR is [test-exempt]. - [ ] I followed the [breaking change policy] and added [Data Driven Fixes] where supported. - [ ] All existing and new tests are passing. If you need help, consider asking for advice on the #hackers-new channel on [Discord]. **Note**: The Flutter team is currently trialing the use of [Gemini Code Assist for GitHub](https://developers.google.com/gemini-code-assist/docs/review-github-code). Comments from the `gemini-code-assist` bot should not be taken as authoritative feedback from the Flutter team. If you find its comments useful you can update your code accordingly, but if you are unsure or disagree with the feedback, please feel free to wait for a Flutter team member's review for guidance on which automated comments should be addressed. <!-- Links --> [Contributor Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#overview [Tree Hygiene]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md [test-exempt]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#tests [Flutter Style Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md [Features we expect every widget to implement]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md#features-we-expect-every-widget-to-implement [CLA]: https://cla.developers.google.com/ [flutter/tests]: https://github.com/flutter/tests [breaking change policy]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#handling-breaking-changes [Discord]: https://github.com/flutter/flutter/blob/main/docs/contributing/Chat.md [Data Driven Fixes]: https://github.com/flutter/flutter/blob/main/docs/contributing/Data-driven-Fixes.md
1 parent 765aa21 commit e6b568a

4 files changed

Lines changed: 117 additions & 163 deletions

File tree

‎packages/flutter/lib/src/cupertino/page_scaffold.dart‎

Lines changed: 22 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -89,10 +89,29 @@ class CupertinoPageScaffold extends StatefulWidget {
8989
State<CupertinoPageScaffold> createState() => _CupertinoPageScaffoldState();
9090
}
9191

92-
class _CupertinoPageScaffoldState extends State<CupertinoPageScaffold> {
93-
void _handleStatusBarTap() {
92+
class _CupertinoPageScaffoldState extends State<CupertinoPageScaffold> with WidgetsBindingObserver {
93+
@override
94+
void initState() {
95+
super.initState();
96+
WidgetsBinding.instance.addObserver(this);
97+
}
98+
99+
@override
100+
void deactivate() {
101+
WidgetsBinding.instance.removeObserver(this);
102+
super.deactivate();
103+
}
104+
105+
@override
106+
void activate() {
107+
super.activate();
108+
WidgetsBinding.instance.addObserver(this);
109+
}
110+
111+
@override
112+
void handleStatusBarTap() {
113+
super.handleStatusBarTap();
94114
final ScrollController? primaryScrollController = PrimaryScrollController.maybeOf(context);
95-
// Only act on the scroll controller if it has any attached scroll positions.
96115
if (primaryScrollController != null && primaryScrollController.hasClients) {
97116
primaryScrollController.animateTo(
98117
0.0,
@@ -187,15 +206,6 @@ class _CupertinoPageScaffoldState extends State<CupertinoPageScaffold> {
187206
right: 0.0,
188207
child: MediaQuery.withNoTextScaling(child: widget.navigationBar!),
189208
),
190-
// Add a touch handler the size of the status bar on top of all contents
191-
// to handle scroll to top by status bar taps.
192-
Positioned(
193-
top: 0.0,
194-
left: 0.0,
195-
right: 0.0,
196-
height: existingMediaQuery.padding.top,
197-
child: GestureDetector(excludeFromSemantics: true, onTap: _handleStatusBarTap),
198-
),
199209
],
200210
),
201211
),

‎packages/flutter/lib/src/material/scaffold.dart‎

Lines changed: 31 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,6 @@ enum _ScaffoldSlot {
7272
floatingActionButton,
7373
drawer,
7474
endDrawer,
75-
statusBar,
7675
}
7776

7877
/// Manages [SnackBar]s and [MaterialBanner]s for descendant [Scaffold]s.
@@ -1273,11 +1272,6 @@ class _ScaffoldLayout extends MultiChildLayoutDelegate {
12731272
}());
12741273
}
12751274

1276-
if (hasChild(_ScaffoldSlot.statusBar)) {
1277-
layoutChild(_ScaffoldSlot.statusBar, fullWidthConstraints.tighten(height: minInsets.top));
1278-
positionChild(_ScaffoldSlot.statusBar, Offset.zero);
1279-
}
1280-
12811275
if (hasChild(_ScaffoldSlot.drawer)) {
12821276
layoutChild(_ScaffoldSlot.drawer, BoxConstraints.tight(size));
12831277
positionChild(_ScaffoldSlot.drawer, Offset.zero);
@@ -2193,7 +2187,8 @@ class Scaffold extends StatefulWidget {
21932187
///
21942188
/// Can display [BottomSheet]s. Retrieve a [ScaffoldState] from the current
21952189
/// [BuildContext] using [Scaffold.of].
2196-
class ScaffoldState extends State<Scaffold> with TickerProviderStateMixin, RestorationMixin {
2190+
class ScaffoldState extends State<Scaffold>
2191+
with TickerProviderStateMixin, RestorationMixin, WidgetsBindingObserver {
21972192
@override
21982193
String? get restorationId => widget.restorationId;
21992194

@@ -2743,10 +2738,13 @@ class ScaffoldState extends State<Scaffold> with TickerProviderStateMixin, Resto
27432738

27442739
// iOS FEATURES - status bar tap, back gesture
27452740

2746-
// On iOS and macOS, if `primary` is true, tapping the status bar scrolls the app's primary scrollable
2741+
// On iOS, if `primary` is true, tapping the status bar scrolls the app's primary scrollable
27472742
// to the top. We implement this by looking up the primary scroll controller and
27482743
// scrolling it to the top when tapped.
2749-
void _handleStatusBarTap() {
2744+
@override
2745+
void handleStatusBarTap() {
2746+
super.handleStatusBarTap();
2747+
assert(widget.primary);
27502748
final ScrollController? primaryScrollController = PrimaryScrollController.maybeOf(context);
27512749
if (primaryScrollController != null && primaryScrollController.hasClients) {
27522750
primaryScrollController.animateTo(
@@ -2787,6 +2785,9 @@ class ScaffoldState extends State<Scaffold> with TickerProviderStateMixin, Resto
27872785
);
27882786

27892787
_bottomSheetScrimAnimationController = AnimationController(vsync: this);
2788+
if (widget.primary) {
2789+
WidgetsBinding.instance.addObserver(this);
2790+
}
27902791
}
27912792

27922793
@protected
@@ -2828,6 +2829,13 @@ class ScaffoldState extends State<Scaffold> with TickerProviderStateMixin, Resto
28282829
_updatePersistentBottomSheet();
28292830
}
28302831
}
2832+
switch ((oldWidget.primary, widget.primary)) {
2833+
case (true, false):
2834+
WidgetsBinding.instance.removeObserver(this);
2835+
case (false, true):
2836+
WidgetsBinding.instance.addObserver(this);
2837+
case (true, true) || (false, false):
2838+
}
28312839
}
28322840

28332841
@protected
@@ -2849,6 +2857,20 @@ class ScaffoldState extends State<Scaffold> with TickerProviderStateMixin, Resto
28492857
super.didChangeDependencies();
28502858
}
28512859

2860+
@override
2861+
void deactivate() {
2862+
WidgetsBinding.instance.removeObserver(this);
2863+
super.deactivate();
2864+
}
2865+
2866+
@override
2867+
void activate() {
2868+
super.activate();
2869+
if (widget.primary) {
2870+
WidgetsBinding.instance.addObserver(this);
2871+
}
2872+
}
2873+
28522874
@protected
28532875
@override
28542876
void dispose() {
@@ -3150,33 +3172,6 @@ class ScaffoldState extends State<Scaffold> with TickerProviderStateMixin, Resto
31503172
removeBottomPadding: true,
31513173
);
31523174

3153-
switch (themeData.platform) {
3154-
case TargetPlatform.iOS:
3155-
case TargetPlatform.macOS:
3156-
if (!widget.primary) {
3157-
break;
3158-
}
3159-
_addIfNonNull(
3160-
children,
3161-
GestureDetector(
3162-
behavior: HitTestBehavior.opaque,
3163-
onTap: _handleStatusBarTap,
3164-
// iOS accessibility automatically adds scroll-to-top to the clock in the status bar
3165-
excludeFromSemantics: true,
3166-
),
3167-
_ScaffoldSlot.statusBar,
3168-
removeLeftPadding: false,
3169-
removeTopPadding: true,
3170-
removeRightPadding: false,
3171-
removeBottomPadding: true,
3172-
);
3173-
case TargetPlatform.android:
3174-
case TargetPlatform.fuchsia:
3175-
case TargetPlatform.linux:
3176-
case TargetPlatform.windows:
3177-
break;
3178-
}
3179-
31803175
if (_endDrawerOpened.value) {
31813176
_buildDrawer(children, textDirection);
31823177
_buildEndDrawer(children, textDirection);

‎packages/flutter/test/cupertino/scaffold_test.dart‎

Lines changed: 32 additions & 58 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55
import 'dart:typed_data';
66

77
import 'package:flutter/cupertino.dart';
8+
import 'package:flutter/services.dart' show SystemChannels;
9+
import 'package:flutter/src/services/message_codecs.dart';
810
import 'package:flutter_test/flutter_test.dart';
911

1012
import '../image_data.dart';
@@ -424,64 +426,6 @@ void main() {
424426
expect(decoration.color, const Color(0xFF010203));
425427
});
426428

427-
testWidgets('Lists in CupertinoPageScaffold scroll to the top when status bar tapped', (
428-
WidgetTester tester,
429-
) async {
430-
await tester.pumpWidget(
431-
CupertinoApp(
432-
builder: (BuildContext context, Widget? child) {
433-
// Acts as a 20px status bar at the root of the app.
434-
return MediaQuery(
435-
data: MediaQuery.of(context).copyWith(padding: const EdgeInsets.only(top: 20)),
436-
child: child!,
437-
);
438-
},
439-
home: CupertinoPageScaffold(
440-
// Default nav bar is translucent.
441-
navigationBar: const CupertinoNavigationBar(middle: Text('Title')),
442-
child: ListView.builder(
443-
itemExtent: 50,
444-
itemBuilder: (BuildContext context, int index) => Text(index.toString()),
445-
),
446-
),
447-
),
448-
);
449-
// Top media query padding 20 + translucent nav bar 44.
450-
expect(tester.getTopLeft(find.text('0')).dy, 64);
451-
expect(tester.getTopLeft(find.text('6')).dy, 364);
452-
453-
await tester.fling(
454-
find.text('5'), // Find some random text on the screen.
455-
const Offset(0, -200),
456-
20,
457-
);
458-
459-
await tester.pumpAndSettle();
460-
461-
expect(tester.getTopLeft(find.text('6')).dy, moreOrLessEquals(166.833, epsilon: 0.1));
462-
expect(
463-
tester.getTopLeft(find.text('12')).dy,
464-
moreOrLessEquals(466.8333333333334, epsilon: 0.1),
465-
);
466-
467-
// The media query top padding is 20. Tapping at 20 should do nothing.
468-
await tester.tapAt(const Offset(400, 20));
469-
await tester.pumpAndSettle();
470-
expect(tester.getTopLeft(find.text('6')).dy, moreOrLessEquals(166.833, epsilon: 0.1));
471-
expect(
472-
tester.getTopLeft(find.text('12')).dy,
473-
moreOrLessEquals(466.8333333333334, epsilon: 0.1),
474-
);
475-
476-
// Tap 1 pixel higher.
477-
await tester.tapAt(const Offset(400, 19));
478-
await tester.pump();
479-
await tester.pump(const Duration(milliseconds: 500));
480-
expect(tester.getTopLeft(find.text('0')).dy, 64);
481-
expect(tester.getTopLeft(find.text('6')).dy, 364);
482-
expect(find.text('12'), findsNothing);
483-
});
484-
485429
testWidgets('resizeToAvoidBottomInset is supported even when no navigationBar', (
486430
WidgetTester tester,
487431
) async {
@@ -588,6 +532,36 @@ void main() {
588532
);
589533
});
590534

535+
testWidgets('Tap the status bar scrolls to top', (WidgetTester tester) async {
536+
final scrollController = ScrollController(initialScrollOffset: 1000);
537+
addTearDown(scrollController.dispose);
538+
await tester.pumpWidget(
539+
CupertinoApp(
540+
home: Builder(
541+
builder: (BuildContext context) {
542+
return PrimaryScrollController(
543+
controller: scrollController,
544+
child: const CupertinoPageScaffold(
545+
child: SingleChildScrollView(primary: true, child: SizedBox(height: 12345)),
546+
),
547+
);
548+
},
549+
),
550+
),
551+
);
552+
final ByteData message = const JSONMethodCodec().encodeMethodCall(
553+
const MethodCall('handleScrollToTop'),
554+
);
555+
tester.binding.defaultBinaryMessenger.handlePlatformMessage(
556+
SystemChannels.statusBar.name,
557+
message,
558+
(ByteData? data) {},
559+
);
560+
await tester.pumpAndSettle();
561+
562+
expect(scrollController.offset, 0.0);
563+
});
564+
591565
testWidgets('CupertinoPageScaffold does not crash at zero area', (WidgetTester tester) async {
592566
await tester.pumpWidget(
593567
const CupertinoApp(

‎packages/flutter/test/material/scaffold_test.dart‎

Lines changed: 32 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -597,23 +597,6 @@ void main() {
597597
);
598598
}
599599

600-
testWidgets(
601-
'Tapping the status bar scrolls to top',
602-
(WidgetTester tester) async {
603-
await tester.pumpWidget(buildStatusBarTestApp(debugDefaultTargetPlatformOverride));
604-
final ScrollableState scrollable = tester.state(find.byType(Scrollable));
605-
scrollable.position.jumpTo(500.0);
606-
expect(scrollable.position.pixels, equals(500.0));
607-
await tester.tapAt(const Offset(100.0, 10.0));
608-
await tester.pumpAndSettle();
609-
expect(scrollable.position.pixels, equals(0.0));
610-
},
611-
variant: const TargetPlatformVariant(<TargetPlatform>{
612-
TargetPlatform.iOS,
613-
TargetPlatform.macOS,
614-
}),
615-
);
616-
617600
testWidgets(
618601
'No status bar when primary is false',
619602
(WidgetTester tester) async {
@@ -692,51 +675,43 @@ void main() {
692675
}),
693676
);
694677

695-
testWidgets(
696-
'Tapping the status bar scrolls to top with ease out curve animation',
697-
(WidgetTester tester) async {
698-
const duration = 1000;
699-
final stops = <double>[0.842, 0.959, 0.993, 1.0];
700-
const double scrollOffset = 1000;
678+
testWidgets('Tapping the status bar scrolls to top with ease out curve animation', (
679+
WidgetTester tester,
680+
) async {
681+
const duration = 1000;
682+
final stops = <double>[0.842, 0.959, 0.993, 1.0];
683+
const double scrollOffset = 1000;
701684

702-
await tester.pumpWidget(buildStatusBarTestApp(debugDefaultTargetPlatformOverride));
703-
final ScrollableState scrollable = tester.state(find.byType(Scrollable));
704-
scrollable.position.jumpTo(scrollOffset);
705-
await tester.tapAt(const Offset(100.0, 10.0));
685+
await tester.pumpWidget(buildStatusBarTestApp(null));
686+
final ScrollableState scrollable = tester.state(find.byType(Scrollable));
687+
scrollable.position.jumpTo(scrollOffset);
706688

707-
await tester.pump(Duration.zero);
708-
expect(scrollable.position.pixels, equals(scrollOffset));
689+
final ByteData message = const JSONMethodCodec().encodeMethodCall(
690+
const MethodCall('handleScrollToTop'),
691+
);
692+
tester.binding.defaultBinaryMessenger.handlePlatformMessage(
693+
SystemChannels.statusBar.name,
694+
message,
695+
(ByteData? data) {},
696+
);
709697

710-
for (var i = 0; i < stops.length; i++) {
711-
await tester.pump(Duration(milliseconds: duration ~/ stops.length));
712-
// Scroll pixel position is very long double, compare with floored int
713-
// pixel position
714-
expect(scrollable.position.pixels.toInt(), equals((scrollOffset * (1 - stops[i])).toInt()));
715-
}
698+
await tester.pump(Duration.zero);
699+
expect(scrollable.position.pixels, equals(scrollOffset));
716700

717-
// Finally stops at the top.
718-
expect(scrollable.position.pixels, equals(0.0));
719-
},
720-
variant: const TargetPlatformVariant(<TargetPlatform>{
721-
TargetPlatform.iOS,
722-
TargetPlatform.macOS,
723-
}),
724-
);
701+
for (var i = 0; i < stops.length; i++) {
702+
await tester.pump(Duration(milliseconds: duration ~/ stops.length));
703+
// Scroll pixel position is very long double, compare with floored int
704+
// pixel position
705+
expect(
706+
scrollable.position.pixels.toInt(),
707+
equals((scrollOffset * (1 - stops[i])).toInt()),
708+
reason: 'stop $i',
709+
);
710+
}
725711

726-
testWidgets(
727-
'Tapping the status bar does not scroll to top',
728-
(WidgetTester tester) async {
729-
await tester.pumpWidget(buildStatusBarTestApp(TargetPlatform.android));
730-
final ScrollableState scrollable = tester.state(find.byType(Scrollable));
731-
scrollable.position.jumpTo(500.0);
732-
expect(scrollable.position.pixels, equals(500.0));
733-
await tester.tapAt(const Offset(100.0, 10.0));
734-
await tester.pump();
735-
await tester.pump(const Duration(seconds: 1));
736-
expect(scrollable.position.pixels, equals(500.0));
737-
},
738-
variant: const TargetPlatformVariant(<TargetPlatform>{TargetPlatform.android}),
739-
);
712+
// Finally stops at the top.
713+
expect(scrollable.position.pixels, equals(0.0));
714+
});
740715

741716
testWidgets('Bottom sheet cannot overlap app bar', (WidgetTester tester) async {
742717
final Key sheetKey = UniqueKey();

0 commit comments

Comments
 (0)