From 9ee00ae168e82742099b2077d4abe580dbf11dda Mon Sep 17 00:00:00 2001 From: Nate Wilson Date: Mon, 4 Nov 2024 09:42:06 -0700 Subject: [PATCH] Fix `NestedScrollView` inner position logic (#157756) closes #40740

NestedScrollController fix

Demo source code

(click to expand)
(this is a slightly more concise version of the code sample from #40740) ```dart import 'package:flutter/material.dart'; void main() { runApp( const MaterialApp( debugShowCheckedModeBanner: false, home: Scaffold(body: NewsScreen()), ), ); } class NewsScreen extends StatelessWidget { const NewsScreen({super.key}); static const List _tabs = ['Featured', 'Popular', 'Latest']; static final List _tabViews = [ for (final String name in _tabs) SafeArea( top: false, bottom: false, child: Builder(builder: (BuildContext context) { final handle = NestedScrollView.sliverOverlapAbsorberHandleFor(context); return NotificationListener( onNotification: (ScrollNotification notification) => true, child: CustomScrollView( key: PageStorageKey(name), slivers: [ SliverOverlapInjector(handle: handle), SliverPadding( padding: const EdgeInsets.all(8.0), sliver: SliverList( delegate: SliverChildBuilderDelegate( childCount: 30, (BuildContext context, int index) => Container( margin: const EdgeInsets.only(bottom: 8), width: double.infinity, height: 150, color: const Color(0xFFB0A4C8), alignment: Alignment.center, child: Text( '$name $index', style: const TextStyle(fontWeight: FontWeight.w600), ), ), ), ), ), ], ), ); }), ), ]; @override Widget build(BuildContext context) { return DefaultTabController( length: _tabs.length, child: NestedScrollView( headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) => [ SliverOverlapAbsorber( handle: NestedScrollView.sliverOverlapAbsorberHandleFor(context), sliver: SliverSafeArea( top: false, sliver: SliverAppBar( title: const Text('Tab Demo'), floating: true, pinned: true, snap: true, forceElevated: innerBoxIsScrolled, bottom: TabBar( tabs: _tabs.map((String name) => Tab(text: name)).toList(), ), ), ), ), ], body: TabBarView(children: _tabViews), ), ); } } ```

This bug can be traced to a return statement inside `_NestedScrollPosition`: ```dart double applyClampedDragUpdate(double delta) { // ... return delta + offset; } ``` Thanks to some quirks of floating-point arithmetic, `applyClampedDragUpdate` would sometimes return a tiny non-zero value, which ends up ruining one of the scroll coordinator's equality checks. https://github.com/flutter/flutter/blob/8990ed6538592fc8aee63b0e137b7b52804a030f/packages/flutter/lib/src/widgets/nested_scroll_view.dart#L658-L664 --- .../lib/src/widgets/nested_scroll_view.dart | 7 +- .../test/widgets/nested_scroll_view_test.dart | 111 ++++++++++++++++++ 2 files changed, 117 insertions(+), 1 deletion(-) diff --git a/packages/flutter/lib/src/widgets/nested_scroll_view.dart b/packages/flutter/lib/src/widgets/nested_scroll_view.dart index 99969beeaf..439f8e4637 100644 --- a/packages/flutter/lib/src/widgets/nested_scroll_view.dart +++ b/packages/flutter/lib/src/widgets/nested_scroll_view.dart @@ -1320,7 +1320,12 @@ class _NestedScrollPosition extends ScrollPosition implements ScrollActivityDele forcePixels(actualNewPixels); didUpdateScrollPositionBy(offset); } - return delta + offset; + + final double result = delta + offset; + if (result.abs() < precisionErrorTolerance) { + return 0.0; + } + return result; } // Returns the overscroll. diff --git a/packages/flutter/test/widgets/nested_scroll_view_test.dart b/packages/flutter/test/widgets/nested_scroll_view_test.dart index 2ae0515403..14139bdf61 100644 --- a/packages/flutter/test/widgets/nested_scroll_view_test.dart +++ b/packages/flutter/test/widgets/nested_scroll_view_test.dart @@ -3628,6 +3628,117 @@ void main() { }); }); + // Regression test for https://github.com/flutter/flutter/issues/40740. + testWidgets('Maintains scroll position of inactive tab', (WidgetTester tester) async { + const List tabs = ['Featured', 'Popular', 'Latest']; + final List tabViews = [ + for (final String name in tabs) + SafeArea( + top: false, + bottom: false, + child: Builder( + builder: (BuildContext context) => CustomScrollView( + key: PageStorageKey(name), + slivers: [ + SliverOverlapInjector( + handle: NestedScrollView.sliverOverlapAbsorberHandleFor(context), + ), + SliverPadding( + padding: const EdgeInsets.all(8.0), + sliver: SliverList( + delegate: SliverChildBuilderDelegate( + childCount: 30, + (BuildContext context, int index) { + return ListTile(title: Text('Item $index')); + }, + ), + ), + ), + ], + ), + ), + ), + ]; + + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: DefaultTabController( + length: tabs.length, + child: NestedScrollView( + headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) => [ + SliverOverlapAbsorber( + handle: NestedScrollView.sliverOverlapAbsorberHandleFor(context), + sliver: SliverSafeArea( + top: false, + sliver: SliverAppBar( + title: const Text('Tab Demo'), + floating: true, + pinned: true, + snap: true, + forceElevated: innerBoxIsScrolled, + bottom: TabBar( + tabs: tabs.map((String name) => Tab(text: name)).toList(), + ), + ), + ), + ), + ], + body: TabBarView(children: tabViews), + ), + ), + ), + ), + ); + + final Finder finder = find.text('Item 14', skipOffstage: false); + final Finder findAny = find.descendant( + of: find.byType(SliverList), + matching: find.byType(ListTile), + ).first; + + Future scroll(VerticalDirection direction) async { + switch (direction) { + case VerticalDirection.down: + while (!tester.any(finder)) { + await tester.fling(find.byType(Scaffold), const Offset(0, -50), 20); + await tester.pumpAndSettle(); + } + await tester.ensureVisible(finder); + case VerticalDirection.up: + await tester.fling(find.byType(Scaffold), const Offset(0, 20), 20); + await tester.pumpAndSettle(); + } + } + + double getScrollPosition() { + return Scrollable.of(tester.element(findAny)).position.pixels; + } + + expect(getScrollPosition(), 0.0); + + // Scroll toward the bottom of Tab 1. + await scroll(VerticalDirection.down); + final double tab1Position = getScrollPosition(); + + // Switch to second tab. + await tester.tap(find.text('Popular')); + await tester.pumpAndSettle(); + + // Scroll toward the bottom of the second tab. + await scroll(VerticalDirection.down); + final double tab2Position = getScrollPosition(); + + // Scroll up a bit in the second tab. + await scroll(VerticalDirection.up); + expect(getScrollPosition(), lessThan(tab2Position)); + + // Switch back to the first tab. + await tester.tap(find.text('Featured')); + await tester.pumpAndSettle(); + expect(getScrollPosition(), tab1Position); + }); + testWidgets('$SliverOverlapAbsorberHandle dispatches creation in constructor', (WidgetTester widgetTester) async { await expectLater( await memoryEvents(() => SliverOverlapAbsorberHandle().dispose(), SliverOverlapAbsorberHandle),