Created
June 4, 2025 19:04
-
-
Save slightfoot/70b86fd21f98c7a92c9fe34e114a6398 to your computer and use it in GitHub Desktop.
Preserve Position Scroll - by Simon Lightfoot :: #HumpdayQandA on 4th June 2025 :: https://www.youtube.com/watch?v=DfMHiEs5j2o
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// MIT License | |
// | |
// Copyright (c) 2025 Simon Lightfoot | |
// | |
// Permission is hereby granted, free of charge, to any person obtaining a copy | |
// of this software and associated documentation files (the "Software"), to deal | |
// in the Software without restriction, including without limitation the rights | |
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | |
// copies of the Software, and to permit persons to whom the Software is | |
// furnished to do so, subject to the following conditions: | |
// | |
// The above copyright notice and this permission notice shall be included in all | |
// copies or substantial portions of the Software. | |
// | |
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | |
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | |
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | |
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | |
// SOFTWARE. | |
// | |
import 'dart:async'; | |
import 'dart:collection'; | |
import 'package:flutter/material.dart'; | |
import 'package:flutter/rendering.dart'; | |
// Cosmin-Mihai Bodnariuc (17:52) | |
// Q: How would you guys implement a feed scroll that would | |
// retain the current scroll offset after inserting new items | |
// at the beginning of the list? | |
void main(List<String> args) { | |
runApp( | |
MaterialApp( | |
debugShowCheckedModeBanner: false, | |
theme: ThemeData.from( | |
colorScheme: ColorScheme.fromSeed( | |
seedColor: Colors.red, | |
dynamicSchemeVariant: DynamicSchemeVariant.vibrant, | |
), | |
useMaterial3: false, | |
), | |
home: const HomeScreen(), | |
), | |
); | |
} | |
class FeedRepository extends ChangeNotifier { | |
FeedRepository() { | |
for (int i = 0; i < 20; i++) { | |
_posts.add(_formatPost(i)); | |
} | |
} | |
final _posts = <String>[]; | |
List<String> get posts => UnmodifiableListView(_posts); | |
Timer? _autoPost; | |
int _autoPostCycle = 0; | |
String _formatPost(int count) { | |
return 'Post $_autoPostCycle :: $count'; | |
} | |
void addPost(int count) { | |
_posts.insert(0, _formatPost(count)); | |
notifyListeners(); | |
} | |
void start() { | |
stop(); | |
++_autoPostCycle; | |
int count = 0; | |
addPost(count++); | |
_autoPost = Timer.periodic(const Duration(seconds: 1), (_) { | |
addPost(count++); | |
}); | |
} | |
void stop() { | |
_autoPost?.cancel(); | |
_autoPost = null; | |
} | |
} | |
class HomeScreen extends StatefulWidget { | |
const HomeScreen({super.key}); | |
@override | |
State<HomeScreen> createState() => _HomeScreenState(); | |
} | |
class _HomeScreenState extends State<HomeScreen> { | |
late final ScrollController controller; | |
final feed = FeedRepository(); | |
@override | |
void initState() { | |
super.initState(); | |
controller = ScrollController(); | |
} | |
@override | |
void dispose() { | |
controller.dispose(); | |
super.dispose(); | |
} | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
backgroundColor: Colors.grey.shade200, | |
appBar: AppBar( | |
title: Text('News Feed'), | |
actions: [ | |
PlayPauseButton( | |
onPlayPause: (bool value) { | |
print('onPlayPause: $value'); | |
if (value) { | |
feed.start(); | |
} else { | |
feed.stop(); | |
} | |
}, | |
), | |
], | |
), | |
body: ListenableBuilder( | |
listenable: feed, | |
builder: (BuildContext context, Widget? child) { | |
final posts = feed.posts; | |
return NewsPostListV2( | |
controller: controller, | |
posts: posts, | |
); | |
}, | |
), | |
); | |
} | |
} | |
class NewsPostListV2 extends StatefulWidget { | |
const NewsPostListV2({ | |
super.key, | |
required this.controller, | |
required this.posts, | |
}); | |
final ScrollController controller; | |
final List<String> posts; | |
@override | |
State<NewsPostListV2> createState() => _NewsPostListV2State(); | |
} | |
class _NewsPostListV2State extends State<NewsPostListV2> { | |
final _viewportKey = GlobalKey(); | |
String? _originPost; | |
void _findNewOriginPost() { | |
final annotatedResult = AnnotationResult<String>(); | |
final layer = _viewportKey.currentContext!.findRenderObject()!.debugLayer! as OffsetLayer; | |
layer.findAnnotations<String>( | |
annotatedResult, | |
layer.offset, | |
onlyFirst: true, | |
); | |
if (annotatedResult.entries.isNotEmpty) { | |
scheduleMicrotask(() { | |
final firstEntry = annotatedResult.entries.first; | |
print('found ${firstEntry.annotation} @ ${firstEntry.localPosition}'); | |
setState(() => _originPost = firstEntry.annotation); | |
widget.controller.position.jumpTo(firstEntry.localPosition.dy); | |
}); | |
} | |
} | |
@override | |
Widget build(BuildContext context) { | |
return NotificationListener<ScrollNotification>( | |
onNotification: (ScrollNotification notification) { | |
if (notification is ScrollEndNotification) { | |
_findNewOriginPost(); | |
} | |
return true; | |
}, | |
child: Scrollable( | |
controller: widget.controller, | |
viewportBuilder: (BuildContext context, ViewportOffset position) { | |
return RepaintBoundary( | |
key: _viewportKey, | |
child: CustomMultiChildLayout( | |
delegate: ListScrollMultiDelegate( | |
position: position, | |
posts: widget.posts, | |
originPost: _originPost, | |
), | |
children: [ | |
for (final post in widget.posts) // | |
LayoutId( | |
id: post, | |
key: Key(post), | |
child: PostCard(post: post), | |
), | |
], | |
), | |
); | |
}, | |
), | |
); | |
} | |
} | |
class ListScrollMultiDelegate extends MultiChildLayoutDelegate { | |
ListScrollMultiDelegate({ | |
required this.position, | |
required this.posts, | |
required this.originPost, | |
}) : super(relayout: position); | |
final ViewportOffset position; | |
final List<String> posts; | |
final String? originPost; | |
@override | |
bool shouldRelayout(covariant ListScrollMultiDelegate oldDelegate) { | |
return position != oldDelegate.position || | |
posts != oldDelegate.posts || | |
originPost != oldDelegate.originPost; | |
} | |
@override | |
Size getSize(BoxConstraints constraints) { | |
position.applyViewportDimension(constraints.maxHeight); | |
position.applyContentDimensions( | |
double.negativeInfinity, | |
double.infinity, | |
); | |
return constraints.biggest; | |
} | |
@override | |
void performLayout(Size size) { | |
final pixelOffset = position.hasPixels ? position.pixels : 0.0; | |
final originIndex = originPost == null ? 0 : posts.indexOf(originPost!); | |
final childConstraints = BoxConstraints.tightFor(width: size.width); | |
double dy1 = -pixelOffset; | |
for (var i = originIndex - 1; i >= 0; i--) { | |
final post = posts[i]; | |
final childSize = layoutChild(post, childConstraints); | |
dy1 -= childSize.height; | |
positionChild(post, Offset(0.0, dy1)); | |
} | |
double dy2 = -pixelOffset; | |
for (var i = originIndex; i < posts.length; i++) { | |
final post = posts[i]; | |
final childSize = layoutChild(post, childConstraints); | |
positionChild(post, Offset(0.0, dy2)); | |
dy2 += childSize.height; | |
} | |
} | |
} | |
class PostCard extends StatelessWidget { | |
const PostCard({ | |
super.key, | |
required this.post, | |
}); | |
final String post; | |
@override | |
Widget build(BuildContext context) { | |
return AnnotatedRegion<String>( | |
value: post, | |
child: Card( | |
color: Colors.accents[post.hashCode % Colors.accents.length], | |
margin: const EdgeInsets.fromLTRB(16.0, 12.0, 16.0, 12.0), | |
child: Padding( | |
padding: const EdgeInsets.fromLTRB(12.0, 24.0, 12.0, 24.0), | |
child: Text(post), | |
), | |
), | |
); | |
} | |
} | |
class PlayPauseButton extends StatefulWidget { | |
const PlayPauseButton({ | |
super.key, | |
required this.onPlayPause, | |
}); | |
final void Function(bool play) onPlayPause; | |
@override | |
State<PlayPauseButton> createState() => _PlayPauseButtonState(); | |
} | |
class _PlayPauseButtonState extends State<PlayPauseButton> with SingleTickerProviderStateMixin { | |
late final AnimationController _controller; | |
bool _flag = false; | |
@override | |
void initState() { | |
super.initState(); | |
_controller = AnimationController( | |
duration: const Duration(milliseconds: 300), | |
vsync: this, | |
); | |
} | |
void _onPressed() { | |
_flag = !_flag; | |
widget.onPlayPause(_flag); | |
if (_flag) { | |
_controller.forward(); | |
} else { | |
_controller.reverse(); | |
} | |
} | |
@override | |
void dispose() { | |
_controller.dispose(); | |
super.dispose(); | |
} | |
@override | |
Widget build(BuildContext context) { | |
return IconButton( | |
onPressed: _onPressed, | |
icon: AnimatedIcon( | |
icon: AnimatedIcons.play_pause, | |
progress: _controller, | |
), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment