call method in one stateful widget from another stateful widget - Flutter

后端 未结 7 972
耶瑟儿~
耶瑟儿~ 2020-11-29 17:59

I have a flutter project that i am working on i cant put the whole code cause its more than 500 lines of code so i will try to ask my question as simply as i acn using the i

7条回答
  •  心在旅途
    2020-11-29 18:34

    You can give this a try, it will call a method defined in Page2 (StatefulWidget) from Page1 (StatefulWidget) widget.

    class Page1 extends StatefulWidget {
      @override
      _Page1State createState() => _Page1State();
    }
    
    class _Page1State extends State {
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: Center(
            child: RaisedButton(
              child: Text("Call page 2 method"),
              onPressed: () => Page2().method(),
            ),
          ),
        );
      }
    }
    
    class Page2 extends StatefulWidget {
      method() => createState().methodInPage2();
    
      @override
      _Page2State createState() => _Page2State();
    }
    
    class _Page2State extends State {
      methodInPage2() => print("method in page 2");
    
      @override
      Widget build(BuildContext context) => Container();
    }
    

提交回复
热议问题