Flutter calling child class function from parent class

前端 未结 4 1350
生来不讨喜
生来不讨喜 2021-01-04 04:01

Code:

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(         


        
4条回答
  •  心在旅途
    2021-01-04 04:53

    Thanks to Günter Zöchbauer for pointing me in right direction. I am using GlobalKey to get the things done. However use GlobalKey with care

    GlobalKey<_HomePageState> globalKey = GlobalKey();
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          home: Scaffold(
            appBar: AppBar(
              leading: IconButton(
                icon: Icon(Icons.help),
                onPressed: () {
                 globalKey.currentState.methodA();
                },
              ),
            ),
            body: HomePage(key: globalKey),
          ),
        );
      }
    }
    class HomePage extends StatefulWidget {
      HomePage({Key key}) : super(key: key);
    
      @override
      _HomePageState createState() => _HomePageState();
    }
    
    class _HomePageState extends State {
      @override
      Widget build(BuildContext context) {
        return Container();
      }
    
      void methodA() {}
    }
    

提交回复
热议问题