Controlling State from outside of a StatefulWidget

前端 未结 7 1031
耶瑟儿~
耶瑟儿~ 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:20

    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.

提交回复
热议问题