Last active
March 14, 2025 05:52
-
-
Save davidhicks980/789047b310e12ef930a9abcbe9b47546 to your computer and use it in GitHub Desktop.
ChangeNotifier state synchronization
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
import 'package:flutter/material.dart'; | |
void main() => runApp(const OverlayApp()); | |
class OverlayApp extends StatelessWidget { | |
const OverlayApp({super.key}); | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
title: 'Flutter Demo', | |
debugShowCheckedModeBanner: false, | |
theme: ThemeData(colorSchemeSeed: Colors.blue), | |
home: const OverlayExample(title: 'Flutter Demo Home Page'), | |
); | |
} | |
} | |
class OverlayExample extends StatefulWidget { | |
final String title; | |
const OverlayExample({super.key, required this.title}); | |
@override | |
State<OverlayExample> createState() => _OverlayExampleState(); | |
} | |
class _OverlayExampleState extends State<OverlayExample> | |
with SingleTickerProviderStateMixin { | |
late final Controller controller = Controller(); | |
final GlobalKey key = GlobalKey(); | |
@override | |
void initState() { | |
super.initState(); | |
controller.addListener((){ | |
// Throws | |
if (controller.isExpanded) { | |
key.currentContext!.findRenderObject(); | |
} | |
}); | |
} | |
void open() { | |
controller.expand(); | |
} | |
void close() { | |
controller.collapse(); | |
} | |
@override | |
void dispose() { | |
controller.dispose(); | |
super.dispose(); | |
} | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
appBar: AppBar(title: Text(widget.title)), | |
body: SizedBox( | |
width: 300, | |
height: 400, | |
child: Stack( | |
children: [ | |
TextButton( | |
onPressed: () { | |
if (controller.isExpanded) { | |
close(); | |
} else { | |
open(); | |
} | |
}, | |
child: Text("Toggle overlay"), | |
), | |
AnimatedBuilder( | |
animation: controller, | |
builder: (context, child) { | |
return Positioned( | |
top: 50, | |
left: 0, | |
child: | |
controller.isExpanded | |
? Container( | |
key: key, | |
color: Colors.blue.shade100, | |
child: const Center( | |
child: FlutterLogo(size: 200.0), | |
), | |
) | |
: SizedBox(), | |
); | |
}, | |
), | |
], | |
), | |
), | |
); | |
} | |
} | |
class Controller extends ChangeNotifier { | |
Controller(); | |
bool _isExpanded = false; | |
void _setExpansionState(bool newValue) { | |
if (newValue != _isExpanded) { | |
_isExpanded = newValue; | |
notifyListeners(); | |
} | |
} | |
bool get isExpanded => _isExpanded; | |
void expand() { | |
_setExpansionState(true); | |
} | |
void collapse() { | |
_setExpansionState(false); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment