尽管定义了Dart“未定义函数”

时间:2018-07-27 22:25:08

标签: dart flutter

我如何正确访问_runThisFunction(...)中的onTap()

...

class _DealList extends State<DealList> with AutomaticKeepAliveClientMixin {

  void _runThisFunction() async {
    print('Run me')
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return FutureBuilder(
      future: _loadingDeals,
      builder: (BuildContext context, AsyncSnapshot snapshot) {
        return snapshot.connectionState == ConnectionState.done
            ? RefreshIndicator(
                onRefresh: _handleRefresh,
                child: ListView.builder(
                  physics: const AlwaysScrollableScrollPhysics(),
                  itemCount: snapshot.data['deals'].length,
                  itemBuilder: (context, index) {
                    final Map deal = snapshot.data['deals'][index];

                    return _getDealItem(deal, context);
                  },
                ),
              )
            : Center(
                child: CircularProgressIndicator(),
              );
      },
    );
  }
}

Container _getDealItem(Map deal, context) {
  return new Container(
    height: 90.0,
    child: Material(
      child: InkWell(
        child: _getDealRow(deal), // <-- this renders the row with the `deal` object
        onTap: () {
          // Below call fails
          // 'The function isn't defined'
          _runThisFunction();

        },
      ),
    ),
  );
}

1 个答案:

答案 0 :(得分:3)

原因是您超出范围。
小提示“函数” 一词始终表示您要调用的函数为 not > 的一部分,而关键字“方法” 则向您表明您要调用的函数是类的一部分。

在您的情况下,_runThisFunction是在_DealList 内部定义的,但是您正试图从外部调用它。
您需要将_getDealItem移入_DealList_runThisFunction

/// In this case both methods [_runThisFunction()] and [_getDealItem()] are defined inside [_DealList].
class _DealList extends State<DealList> with AutomaticKeepAliveClientMixin {
   void _runThisFunction() ...

   Container _getDealItem() ...
}

/// In this case both functions are defined globally.
void _runThisFunction() ...

Container _getDealItem() ...

您需要确保对_getDealRow和其他嵌套调用也应用相同的逻辑。

相关问题