Search code examples
dartflutterinherited-widget

Using ancestorInheritedElementForWidgetOfExactType in flutter


I have a chat object in a InheritedWidget above to root widget of my app. I want to access this object within initState to set the initial state of a child widget. I've the following code:

void initState() {
  super.initState();
  final inheritedWidget = context.ancestorInheritedElementForWidgetOfExactType(MyInheritedWidget).widget;

  inheritedWidget.chat.someFunction();
}

I'm getting an error saying: "The getter 'chat' isn't defined for the class 'InheritedWidget'

Am I using the method wrong, how do you use it?


Solution

  • You have to cast widget first:

    final inheritedWidget = context.ancestorInheritedElementForWidgetOfExactType(MyInheritedWidget).widget as MyInheritedWidget;