Flutter calling child class function from parent class

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

Code:

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


        
4条回答
  •  轮回少年
    2021-01-04 04:48

    The above answer did not work for me, instead i just replaced the global key and it worked very well:

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

    Hope everything is working:)

提交回复
热议问题