Created
May 14, 2025 18:14
-
-
Save slightfoot/7f9fc1f64d305bb9653f8613d8372048 to your computer and use it in GitHub Desktop.
Custom Scrolling Offsets - by Simon Lightfoot :: #HumpdayQandA on 14th May 2025 :: https://www.youtube.com/watch?v=D9y5G3LmrSY
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: HomeScreen(), | |
), | |
); | |
} | |
class FeedRepository extends ChangeNotifier { | |
FeedRepository() { | |
for (int i = 0; i < 50; i++) { | |
addPost(i); | |
} | |
} | |
final _posts = <String>[]; | |
List<String> get posts => UnmodifiableListView(_posts); | |
Timer? _autoPost; | |
int _autoPostCycle = 0; | |
void addPost(int count) { | |
final post = 'Post $_autoPostCycle :: $count'; | |
_posts.add(post); | |
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 CustomScrollController controller; | |
final feed = FeedRepository(); | |
@override | |
void initState() { | |
super.initState(); | |
controller = CustomScrollController(); | |
} | |
@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 NewsPostList( | |
controller: controller, | |
posts: posts, | |
); | |
}, | |
), | |
); | |
} | |
} | |
class NewsPostList extends StatefulWidget { | |
const NewsPostList({ | |
super.key, | |
required this.controller, | |
required this.posts, | |
}); | |
final CustomScrollController controller; | |
final List<String> posts; | |
@override | |
State<NewsPostList> createState() => _NewsPostListState(); | |
} | |
class _NewsPostListState extends State<NewsPostList> { | |
final _viewportKey = GlobalKey(); | |
String? originPost; | |
@override | |
Widget build(BuildContext context) { | |
return NotificationListener<ScrollNotification>( | |
onNotification: (ScrollNotification notification) { | |
if (notification is ScrollEndNotification) { | |
final annotatedResult = AnnotationResult<String>(); | |
final layer = _viewportKey.currentContext!.findRenderObject()!.debugLayer!; | |
layer.findAnnotations<String>( | |
annotatedResult, | |
Offset.zero, | |
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); | |
}); | |
}); | |
} | |
} | |
return true; | |
}, | |
child: Scrollable( | |
controller: widget.controller, | |
axisDirection: AxisDirection.down, | |
viewportBuilder: (BuildContext context, ViewportOffset position) { | |
return Viewport( | |
key: _viewportKey, | |
offset: position, | |
axisDirection: AxisDirection.down, | |
anchor: 0.0, | |
center: originPost != null ? Key(originPost!) : null, | |
slivers: [ | |
for (final post in widget.posts) // | |
SliverToBoxAdapter( | |
key: Key(post), | |
child: AnnotatedRegion<String>( | |
value: post, | |
child: Builder( | |
builder: (context) { | |
return Card( | |
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 CustomScrollController extends ScrollController { | |
CustomScrollController({ | |
super.initialScrollOffset, | |
super.keepScrollOffset, | |
super.debugLabel, | |
super.onAttach, | |
super.onDetach, | |
}); | |
@override | |
ScrollPosition createScrollPosition( | |
ScrollPhysics physics, | |
ScrollContext context, | |
ScrollPosition? oldPosition, | |
) { | |
return CustomScrollPosition( | |
physics: physics, | |
context: context, | |
initialPixels: initialScrollOffset, | |
keepScrollOffset: keepScrollOffset, | |
oldPosition: oldPosition, | |
debugLabel: debugLabel, | |
); | |
} | |
} | |
class CustomScrollPosition extends ScrollPositionWithSingleContext { | |
CustomScrollPosition({ | |
required super.physics, | |
required super.context, | |
super.initialPixels, | |
super.keepScrollOffset, | |
super.oldPosition, | |
super.debugLabel, | |
}); | |
@override | |
double get minScrollExtent => -double.infinity; | |
@override | |
double get maxScrollExtent => double.infinity; | |
} | |
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