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

后端 未结 7 969
耶瑟儿~
耶瑟儿~ 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:33

    Here HomePage is parent page and ChildPage is child page. There is one method called onSelectItem, which we need to call from child page.

    class HomePage extends StatefulWidget {
    
      @override HomePageState createState() => HomePageState();
    }
    
    class HomePageState extends State {
    
      onSelectItem(String param) {
        print(param);
      }
    
      @override Widget build(BuildContext context) {
    
      }
    }
    
    class ChildPage extends StatefulWidget {
      final HomePageState homePageState;
    
      ChildPage({Key key, @required this.homePageState}) : super(key: key);
    
      _ChildPageState createState() => _ChildPageState();
    }
    
    class _ChildPageState extends State {
      @override Widget build(BuildContext context) {
    
        return RaisedButton(
          onPressed: () {
            widget.homePageState.onSelectItem("test");
          },
          child: const Text(
              'Click here',
              style: TextStyle(fontSize: 20)
          ),
        );
      }
    }
    

    So, by using the widget and parent class state we can call the parent class method.

提交回复
热议问题