Skip to content

Instantly share code, notes, and snippets.

@teerasej
Created October 10, 2021 08:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save teerasej/27924db948e684a50986b7878a539589 to your computer and use it in GitHub Desktop.
Save teerasej/27924db948e684a50986b7878a539589 to your computer and use it in GitHub Desktop.
If you want to looking for specific type of ancestor widget (yes, parent widget) you can use following methods below.
// If you're familair with 'parent' term, Flutter call its as 'ancestor'
import 'package:flutter/material.dart';
class NextflowExampleFindParentWidget extends StatefulWidget {
NextflowExampleFindParentWidget({Key? key}) : super(key: key);
@override
_NextflowExampleFindParentWidgetState createState() =>
_NextflowExampleFindParentWidgetState();
}
class _NextflowExampleFindParentWidgetState
extends State<NextflowExampleFindParentWidget> {
Widget _targetParentOrAncestor = Widget();
@override
Widget build(BuildContext context) {
// This method will pass this widget's ancestor (yes, parent) one by one, according to widget tree
context.visitAncestorElements((element) {
var parentWidget = element.widget;
// for example, we are looking for ListView that is higher in Widget tree
if (parentWidget is ListView) {
_targetParentOrAncestor = parentWidget;
return false;
}
return true;
});
return Container();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment