Last active
April 30, 2025 17:28
-
-
Save slightfoot/0761038ed3afeb3aa899646d5a1c60b5 to your computer and use it in GitHub Desktop.
Localizations and deferred loading - by Simon Lightfoot :: #HumpdayQandA on 23rd April 2025 :: https://www.youtube.com/watch?v=XRuKywXD7zM
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 'dart:convert'; | |
import 'package:flutter/material.dart'; | |
import 'package:flutter/scheduler.dart' show SchedulerBinding; | |
import 'package:flutter/services.dart' | |
show SystemChrome, SystemUiMode, SystemUiOverlayStyle, rootBundle; | |
import 'package:flutter_localizations/flutter_localizations.dart'; | |
import 'package:intl/intl.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? | |
class AppLocalizations { | |
AppLocalizations(this._translations); | |
final Map<String, String> _translations; | |
static const delegate = AppLocalizationsDelegate(); | |
String get appTitle => _translations['appTitle']!; | |
String get feedStarted => _translations['feedStarted']!; | |
String durationInHours(int hours) { | |
return Intl.plural( | |
hours, | |
zero: 'none', | |
one: '1 hour', | |
other: '$hours hours', | |
); | |
} | |
} | |
class AppLocalizationsDelegate extends LocalizationsDelegate<AppLocalizations> { | |
const AppLocalizationsDelegate(); | |
static const supportedLocales = [Locale('en'), Locale('es')]; | |
@override | |
bool isSupported(Locale locale) { | |
return switch (locale.languageCode) { | |
'en' || 'es' => true, | |
_ => false, | |
}; | |
} | |
@override | |
Future<AppLocalizations> load(Locale locale) async { | |
final language = locale.languageCode; | |
print('loading translations $language'); | |
final assetData = await rootBundle.loadString( | |
'assets/translations/$language.json', | |
); | |
return AppLocalizations( | |
(json.decode(assetData) as Map).cast<String, String>(), | |
); | |
} | |
@override | |
bool shouldReload(covariant LocalizationsDelegate<AppLocalizations> old) => true; | |
} | |
extension BuildContextTranslation on BuildContext { | |
AppLocalizations get localizations { | |
return Localizations.of<AppLocalizations>(this, AppLocalizations)!; | |
} | |
} | |
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(), | |
localizationsDelegates: [ | |
AppLocalizations.delegate, | |
GlobalMaterialLocalizations.delegate, | |
GlobalWidgetsLocalizations.delegate, | |
GlobalCupertinoLocalizations.delegate, | |
], | |
supportedLocales: AppLocalizationsDelegate.supportedLocales, | |
), | |
); | |
} | |
class MessageEvent { | |
const MessageEvent(this.message); | |
final String Function(BuildContext context) message; | |
} | |
class FeedRepository extends ChangeNotifier { | |
FeedRepository() { | |
for (int i = 0; i < 500; i++) { | |
addPost(i); | |
} | |
} | |
final _events = StreamController<MessageEvent>.broadcast(); | |
Stream<MessageEvent> get messageStream => _events.stream; | |
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++); | |
}); | |
_events.add( | |
MessageEvent((context) => context.localizations.feedStarted), | |
); | |
} | |
void stop() { | |
_autoPost?.cancel(); | |
_autoPost = null; | |
} | |
} | |
class HomeScreen extends StatefulWidget { | |
const HomeScreen({super.key}); | |
@override | |
State<HomeScreen> createState() => _HomeScreenState(); | |
} | |
class _HomeScreenState extends State<HomeScreen> { | |
final feed = FeedRepository(); | |
late StreamSubscription<MessageEvent> _messageSub; | |
@override | |
void initState() { | |
super.initState(); | |
_messageSub = feed.messageStream.listen(_onMessageEvent); | |
SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge); | |
} | |
void _onMessageEvent(MessageEvent event) { | |
ScaffoldMessenger.of(context).showSnackBar( | |
SnackBar(content: Text(event.message(context))), | |
); | |
} | |
@override | |
void dispose() { | |
_messageSub.cancel(); | |
super.dispose(); | |
} | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
appBar: AppBar( | |
title: Text(context.localizations.appTitle), | |
actions: [ | |
PlayPauseButton( | |
onPlayPause: (bool value) { | |
print('onPlayPause: $value'); | |
if (value) { | |
feed.start(); | |
} else { | |
feed.stop(); | |
} | |
}, | |
), | |
], | |
systemOverlayStyle: SystemUiOverlayStyle.light.copyWith( | |
statusBarColor: Colors.transparent, | |
systemNavigationBarColor: Colors.transparent, | |
), | |
), | |
body: PostCache( | |
child: ListenableBuilder( | |
listenable: feed, | |
builder: (BuildContext context, Widget? child) { | |
final posts = feed.posts; | |
return NotificationListener( | |
onNotification: (ScrollNotification notification) { | |
// print('scroll: $notification'); | |
return true; | |
}, | |
child: ListView.builder( | |
itemCount: feed.posts.length, | |
itemBuilder: (BuildContext context, int index) { | |
final post = posts[index]; | |
return PostTile( | |
index: index, | |
post: post, | |
); | |
}, | |
), | |
); | |
}, | |
), | |
), | |
); | |
} | |
} | |
class PostCache extends StatefulWidget { | |
const PostCache({ | |
super.key, | |
required this.child, | |
}); | |
final Widget child; | |
static Map<int, String> cacheOf(BuildContext context) { | |
return context.findAncestorStateOfType<_PostCacheState>()!.cache; | |
} | |
@override | |
State<PostCache> createState() => _PostCacheState(); | |
} | |
class _PostCacheState extends State<PostCache> { | |
final cache = <int, String>{}; | |
@override | |
Widget build(BuildContext context) => widget.child; | |
} | |
class PostTile extends StatefulWidget { | |
const PostTile({ | |
super.key, | |
required this.index, | |
required this.post, | |
}); | |
final int index; | |
final String post; | |
@override | |
State<PostTile> createState() => _PostTileState(); | |
} | |
class _PostTileState extends State<PostTile> { | |
late Map<int, String> _cache; | |
String? _result; | |
Future<String>? _future; | |
@override | |
void initState() { | |
super.initState(); | |
_cache = PostCache.cacheOf(context); | |
_result = _cache[widget.index]; | |
if (_result != null) { | |
_future = Future.value(_result); | |
} | |
} | |
@override | |
void didChangeDependencies() { | |
super.didChangeDependencies(); | |
_load(); | |
} | |
void _load() { | |
if (_result != null || !mounted) { | |
return; | |
} | |
if (Scrollable.recommendDeferredLoadingForContext(context, axis: Axis.vertical)) { | |
SchedulerBinding.instance.scheduleFrameCallback((_) { | |
scheduleMicrotask(() => _load()); | |
}); | |
return; | |
} | |
print('loading ${widget.index}'); | |
setState(() { | |
_future = Future.delayed(const Duration(seconds: 2), () { | |
final result = '${widget.index}'; | |
_cache[widget.index] = result; | |
return result; | |
}); | |
}); | |
} | |
@override | |
Widget build(BuildContext context) { | |
return ListTile( | |
key: Key(widget.post), | |
title: Text(widget.post), | |
trailing: FutureBuilder( | |
initialData: _result, | |
future: _future, | |
builder: (BuildContext context, AsyncSnapshot<String> snapshot) { | |
final result = snapshot.data; | |
if (result == null) { | |
return SizedBox.shrink(); | |
} else { | |
return SizedBox.square( | |
dimension: 48.0, | |
child: ColoredBox( | |
color: Colors.accents[widget.index % Colors.accents.length], | |
child: Center( | |
child: Text(result), | |
), | |
), | |
); | |
} | |
}, | |
), | |
); | |
} | |
} | |
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