首页 > 解决方案 > 将回调从模型传递到 Flutter 中的 GestureDetector 的语法

问题描述

我试图弄清楚如何将 onTap 回调从一个类传递到另一个类。

我创建了一个用于构建列表的模型,在该模型中有一个 onTap 属性,我想做的是定义哪个回调给您,然后从视图中访问 on tap。

持有回调的模型

class MasterListsModel{
  final ListRowType rowType;
  final String assetName;
  final String name;
  final Color textColor;
  final Color backgroundColor;
  final void onTap; // <<------ The property that holds the callback

列表定义示例

List<MasterListsModel> rows(Store<PrimeAppStateModel> store){
    List<MasterListsModel> list = [
      new MasterListsModel(
        ListRowType.headlinePrime,
        name: l10n.d1SearchHeader
      ),
      new MasterListsModel(ListRowType.icon,
        name: l10n.d1SearchMembers,
        textColor: hColors.white,
        assetName: hGraphics.segmentIconMembersWhite,
        backgroundColor: hColors.transparent,
        onTap: someVoidCallBackHere // <<----- The callback added to model
      ),

然后我想从我的列表构造类中唤起 onTap。

return new Container(
      margin: new EdgeInsets.fromLTRB(35.0, 20.0, 0.0, 20.0),
      child: new GestureDetector(
        onTap: masterListModel.onTap, // << ----- Add callback
        child: new Row(
          children: <Widget>[
            new Container(

标签: flutter

解决方案


使用类型VoidCallback而不是void在模型中声明回调。

您还可以使用创建自己的回调类型typedef

typedef void MyCallback({String title});

推荐阅读