I\'m trying to understand the best practice for controlling a StatefulWidget\'s state outside of that Widgets State.
I have the following interface defined.
<
While trying to solve a similar problem, I discovered that ancestorStateOfType()
and TypeMatcher
have been deprecated. Instead, one has to use findAncestorStateOfType()
. However as per the documentation, "calling this method is relatively expensive". The documentation for the findAncestorStateOfType()
method can be found here.
In any case, to use findAncestorStateOfType()
, the following can be implemented (this is a modification of the correct answer using the findAncestorStateOfType()
method):
class StartupPage extends StatefulWidget {
static _StartupPageState of(BuildContext context) => context.findAncestorStateOfType<_StartupPageState>();
@override
_StartupPageState createState() => new _StartupPageState();
}
class _StartupPageState extends State {
...
}
The state can be accessed in the same way as described in the correct answer (using StartupPage.of(context).yourFunction()
). I wanted to update the post with the new method.