Skip to content

Instantly share code, notes, and snippets.

@lukepighetti
Created August 25, 2022 19:08
Show Gist options
  • Save lukepighetti/23e630f310d3c891f01fc2de6298c67f to your computer and use it in GitHub Desktop.
Save lukepighetti/23e630f310d3c891f01fc2de6298c67f to your computer and use it in GitHub Desktop.
A way to update AppBar title based on what ListTile is being occluded https://twitter.com/luke_pighetti/status/1562871407960522755
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final scaffoldKey = GlobalKey();
final appBarKey = GlobalKey();
final controller = ScrollController();
var _title = "August";
@override
void initState() {
controller.addListener(_onScroll);
super.initState();
}
@override
void dispose() {
controller.dispose();
super.dispose();
}
void _onScroll() {
final appBarBottomCenter =
appBarKey.currentContext?.findRenderObject()?.paintBounds.bottomCenter;
if (appBarBottomCenter != null) {
final result = scaffoldKey.currentContext
?.findRenderObject()
// shhhhhhhh
// ignore: invalid_use_of_protected_member
?.layer
?.find<String>(appBarBottomCenter);
if (result != null) {
setState(() {
_title = result;
});
}
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
key: scaffoldKey,
appBar: AppBar(
key: appBarKey,
title: Text(_title),
),
body: ListView(
controller: controller,
children: [
for (final month in ["August", "September"])
for (final day in [
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
23,
24,
25,
26,
27,
28,
29,
30
])
AnnotatedRegion<String>(
value: month,
child: ListTile(
title: Text('$month $day'),
),
)
],
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment