首页 > 解决方案 > 如何在 Flutter 中调用 void 函数而不传递参数?

问题描述

我是 Flutter 的新手,正在学习 Udacity 的介绍课程。在其中一项任务中,我试图遵循代码,但我无法理解它。这是项目解决方案中的代码(我已经剪切并粘贴了重要的部分,还有法律免责声明我不拥有任何这些代码,它来自示例 Flutter Udacity 项目):

Widget build(BuildContext context) {
    final input = Padding(
      padding: _padding,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [

          TextField(...),

          _createDropdown(_fromValue.name, _updateFromConversion),
        ],
      ),
    );
}

void _updateFromConversion(dynamic unitName) {
    setState(() {
      _fromValue = _getUnit(unitName);
    });
    if (_inputValue != null) {
      _updateConversion();
    }
  }

Widget _createDropdown(String currentValue, ValueChanged<dynamic> onChanged) {
    return Container(
      margin: EdgeInsets.only(top: 16.0),
      decoration: BoxDecoration(...),

      padding: EdgeInsets.symmetric(vertical: 8.0),
      child: Theme(...),

        child: DropdownButtonHideUnderline(
          child: ButtonTheme(
            alignedDropdown: true,
            child: DropdownButton(
              value: currentValue,
              items: _unitMenuItems,
              onChanged: onChanged,
              style: Theme.of(context).textTheme.title,
            ),
          ),
        ),
      ),
    );
}

这就是我卡住的地方。_updateFromConversion 需要输入参数 unitName。但是当他们调用它时,在 _createDropdown 中,他们没有传递任何东西。那么 _updateFromConversion 是如何知道 unitName 是什么的呢?此外,_updateFromConversion 是在 _createDropdown 之前执行,还是在设置 DropdownButton 的“onChanged”属性时执行?

第二个问题:他们将返回类型为 void 的函数传递给 _createDropdown,它期待 ValueChanged。这不应该引发错误吗?

如果有人可以解释此代码的流程以及我所缺少的内容,我将不胜感激。谢谢!

标签: flutterdartvaluechangelistener

解决方案


亚什温,

在 dart 中,函数可以作为参数传递给其他函数。例如,这通常用于传递回调。

在您提供的示例中,函数 _updateFromConversion 作为参数 onChanged 传递给另一个函数 _createDropdown。

在该函数中,它将分配给 DropdownButton 按钮的 onChanged 侦听器。

每次 DropdownButton 的值发生变化时,都会调用该函数,并传递 DropdownButton 的选定值。


推荐阅读