Controlling State from outside of a StatefulWidget

前端 未结 7 1046
耶瑟儿~
耶瑟儿~ 2020-11-29 18:44

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.

<
7条回答
  •  甜味超标
    2020-11-29 19:23

    You can expose the state's widget with a static method, a few of the flutter examples do it this way and I've started using it as well:

    class StartupPage extends StatefulWidget {
      static _StartupPageState of(BuildContext context) => context.ancestorStateOfType(const TypeMatcher<_StartupPageState>());
    
      @override
      _StartupPageState createState() => new _StartupPageState();
    }
    
    class _StartupPageState extends State {
      ...
    }
    

    You can then access the state by calling StartupPage.of(context).doSomething();.

    The caveat here is that you need to have a BuildContext with that page somewhere in its tree.

提交回复
热议问题