如何从另一个类中定义的平面按钮的onPressed调用主类('_MyHomePageState()')中定义的方法?

问题描述 投票:0回答:2

我有主类_MyHomePageState(),其中为主页定义了支架,并且我定义了非常小的小部件,它将在新类中进入支架。现在,我必须从主类中FlatButton的onPressed调用主类中定义的函数/方法。

主类中的函数会触发BottomSheet,底部工作表的代码被写入新的dart文件中。

当我在脚手架内正常编写平按钮按钮代码并调用该函数时,它确实会触发底部工作表。

这是代码段:

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final GlobalKey<ScaffoldState> scaffoldKey = GlobalKey<ScaffoldState>();

  ///This below is the function
  void openBottomSheet() {
    var sheetController = scaffoldKey.currentState
        .showBottomSheet((context) => BottomSheetWidget());
    sheetController.closed.then((value) {
      print("Bottom Sheet Closed");
    });
  }

  @override
  Widget build(BuildContext context) {

    // TODO: implement build
    return Scaffold(
      key: scaffoldKey,
      appBar: AppBar(
        title: Text("Hello,World"),
      ),
      backgroundColor: Colors.grey[800],
      body: Stack(children: <Widget>[
        Container(
          height: MediaQuery.of(context).size.height,
          width: MediaQuery.of(context).size.width,
          color: Colors.blueGrey,
        ),
        Column(
          children: <Widget>[
            TopMenu(),
            ButtonClass(),
          ],
        ),
      ]),
    );
  }
}

这里是按钮类:

class ButtonClass extends StatefulWidget {
  _ButtonClassState createState() => _ButtonClassState();

}

class _ButtonClassState extends State<ButtonClass> {

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        children: <Widget>[
          //Container(color: Colors.blue, child: Text("Hello,World")),
          Container(
            height: 50,
            width:100,
            margin: EdgeInsets.all(10.0),
            child: FlatButton(
              onPressed: (){
                ///And I am trying to call that function here, but is not working
                _MyHomePageState().openBottomSheet();
              },
              child: Container(
                color: Colors.red,
              ),
            ),
          ),
        ],
      ),
    );
  }
}
flutter dart flutter-layout
2个回答
0
投票

我确实相信您必须将该功能从主页传递到按钮。

    class ButtonClass extends StatefulWidget {
    final Function onPress;
    const ButtonClass({this.onPress});
           //...
           //...
            child: FlatButton(
              onPressed: onPress,
              child: Container(
                color: Colors.red,
              ),
            ),
          ),
        ],
        ),
       );
      }
        }

并且在您的主要班级中称呼它

ButtonClass(onPress: ()=>openBottomSheet())

0
投票

您可以在子Button类中接受一个函数参数,然后从您的父类_MyHomePageState传递所需的函数。

© www.soinside.com 2019 - 2024. All rights reserved.