Code:

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() {}
}

Question: 我想从IconButtononPressed()methodA().我该怎么做呢?我知道如何从子类调用父类的方法,但是这个用例是不同的.

推荐答案

感谢Günter Zöchbauer为我指明了正确的方向.我用GlobalKey来完成任务.但是使用GlobalKeycare

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() {}
}

Flutter相关问答推荐

使用Flutter,使用Photoshop下载的二进制文件(wav)发生意外转换

如何在SingleChildScrollView中使用GridView

在Flutter 动中绘制ECG图

更改BottomNavigationBar onTap?的大小

什么是dart :这只是dart ?

悬停时打开Flutter 下拉按钮

上传的图像不能在FireBase中预览.S档案类型为空白,摆动

TextField 中的富文本并获取 RenderParagraph

如何使自动焦点位于已经有一些文本的 TextField 的第一行?

找不到任何与 com.google.firebase:firebase-sessions:[15.0.0, 16.0.0) 匹配的版本

Flutter列顶部和底部出现不必要的边距问题

像图像一样Flutter 自定义标签

什么最接近 Dart 的 List.asMap().forEach() 返回列表?

Freezed+BLoc 如何从 BLoc Listener 查看当前状态和特定状态的变量

如何使用 riverpod_annotation 创建非自动处置提供程序?

有什么办法可以消除Flutter 中的传递依赖?

如何更改中心的圆形进度指示器

我怎样才能一次只选中一个复选框?

Firebase 中的查询限制 - .orderBy() 错误

如何使用 Row 和 Column 制作 L 形布局?