Controlling State from outside of a StatefulWidget

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

    There is another common used approach to have access to State's properties/methods:

    class StartupPage extends StatefulWidget {
      StartupPage({Key key}) : super(key: key);
    
      @override
      StartupPageState createState() => StartupPageState();
    }
    
    // Make class public!
    class StartupPageState extends State {
      int someStateProperty;
    
      void someStateMethod() {}
    }
    
    // Somewhere where inside class where `StartupPage` will be used
    final startupPageKey = GlobalKey();
    
    // Somewhere where the `StartupPage` will be opened
    final startupPage = StartupPage(key: startupPageKey);
    Navigator.push(context, MaterialPageRoute(builder: (_) => startupPage);
    
    // Somewhere where you need have access to state
    startupPageKey.currentState.someStateProperty = 1;
    startupPageKey.currentState.someStateMethod();
    

提交回复
热议问题