Created
December 18, 2023 13:54
-
-
Save pskink/115c546eaa8eb91d46b9877d0fc9c32f to your computer and use it in GitHub Desktop.
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
/* | |
sample usage: | |
@override | |
Widget build(BuildContext context) { | |
// finds multiple instances of EditableTextState: | |
return DumbVisitor( | |
onFound: (EditableTextState ets) { | |
print('=' * 60); | |
print('1 $ets'); | |
print('2 ${ets.renderEditable}'); | |
final key = ets.context.findAncestorWidgetOfExactType<TextField>()?.key as ValueKey?; | |
print('3 ${key?.value}'); | |
}, | |
child: const Column( | |
children: [ | |
TextField(key: ValueKey('first key')), | |
TextField(key: ValueKey('second key')), | |
], | |
), | |
); | |
} | |
*/ | |
class DumbVisitor<T> extends StatelessWidget { | |
const DumbVisitor({ | |
super.key, | |
required this.onFound, | |
required this.child, | |
}); | |
final void Function(T object) onFound; | |
final Widget child; | |
@override | |
Widget build(BuildContext context) => child; | |
@override | |
StatelessElement createElement() => _DumbVisitorElement<T>(this, onFound); | |
} | |
class _DumbVisitorElement<T> extends StatelessElement { | |
_DumbVisitorElement(super.widget, this.onFound); | |
final void Function(T object) onFound; | |
Element? oldElement; | |
@override | |
Element? updateChild(Element? child, Widget? newWidget, Object? newSlot) { | |
final element = super.updateChild(child, newWidget, newSlot); | |
if (oldElement != element) { | |
oldElement = element; | |
element?.visitChildren(_visitor); | |
} | |
return element; | |
} | |
void _visitor(Element child) { | |
if (child is StatefulElement && child.state is T) { | |
onFound(child.state as T); | |
} else | |
if (child.renderObject is T) { | |
onFound(child.renderObject as T); | |
} | |
child.visitChildren(_visitor); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment