flutter - 如何在 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。这不应该引发错误吗?
如果有人可以解释此代码的流程以及我所缺少的内容,我将不胜感激。谢谢!
解决方案
亚什温,
在 dart 中,函数可以作为参数传递给其他函数。例如,这通常用于传递回调。
在您提供的示例中,函数 _updateFromConversion 作为参数 onChanged 传递给另一个函数 _createDropdown。
在该函数中,它将分配给 DropdownButton 按钮的 onChanged 侦听器。
每次 DropdownButton 的值发生变化时,都会调用该函数,并传递 DropdownButton 的选定值。
推荐阅读
- javascript - 使用 javascript 或 rxjs 递归过滤嵌套的 json 数据
- bash - Bash 函数 | 更新变量而不在终端中回显
- visual-studio-code - VS Code 代码自动补全高亮
- android - 增加滚动时折叠工具栏布局的大小
- java - 如何使用 MpAndroidChart -Pie Chart 在 android 中显示标签
- javascript - 动态 CRM Netzwerk
- java - Infinispan 不会将缓存实体删除复制到非协调节点
- flutter - 我们如何从 Flutter 中的自定义小部件中获取价值
- c# - 我收到此错误“没有 'IEnumerable 类型的 ViewData 项
' 具有键 'Branch_Name" - python - PyTorch 相当于 numpy 的 np.random.RandomState