从父类颤振调用子类函数 [英] Flutter calling child class function from parent class
本文介绍了从父类颤振调用子类函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
代码:
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
leading: IconButton(
icon: Icon(Icons.help),
onPressed: () {
// how can I call methodA from here?
},
),
),
body: HomePage(),
),
);
}
}
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
@override
Widget build(BuildContext context) {
return Container();
}
void methodA() {}
}
问题:
我想从 onPressed()$ c调用
methodA()
IconButton
中的$ c>。我该怎么做,我知道如何从子类中调用父级的方法,但是这种用例是不同的。
Question:
I want to call methodA()
from onPressed()
of IconButton
. How can I do that, I know how to call parent's method from child class but this use case is different.
推荐答案
感谢GünterZöchbauer将我指向正确的方向。我正在使用 GlobalKey
来完成任务。但是,将 GlobalKey
与护理
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<HomePage> {
@override
Widget build(BuildContext context) {
return Container();
}
void methodA() {}
}
这篇关于从父类颤振调用子类函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文