在阅读 dart 代码时,我经常看到一些仅使用下划线 _ 参数调用的函数。它让我烦恼了一段时间,并且由于 flutter 改进了它的分析消息,我有一些线索......但我觉得我并没有真正掌握这个概念:-(
昨天我写了以下内容进行测试:
when(mockDevice.getLocalPath()).thenAnswer(() async => fileFolder);
Run Code Online (Sandbox Code Playgroud)
并得到以下分析
错误:无法将参数类型“Future Function()”分配给参数类型“Future Function(Invocation)”。
添加下划线时,它工作正常。
when(mockDevice.getLocalPath()).thenAnswer((_) async => fileFolder);
Run Code Online (Sandbox Code Playgroud)
我遇到的最可怕的例子来自@remi rousselet 编写的 provider package
builder: (_, counter, __) => Translations(counter.value),
Run Code Online (Sandbox Code Playgroud)
它来自提供者示例:
Widget build(BuildContext context) {
return MultiProvider(
providers: [
ChangeNotifierProvider(builder: (_) => Counter()),
ProxyProvider<Counter, Translations>(
builder: (_, counter, __) => Translations(counter.value),
),
],
child: Foo(),
);
}
class Translations {
const Translations(this._value);
final int _value;
String get title => 'You clicked $_value times';
}
Run Code Online (Sandbox Code Playgroud)
Cop*_*oad 16
下划线通常表示您不会在块内使用该参数,这只是编写代码的好方法,例如:
method(int useful, int useless) {
// say I am only going to use 'useful' in this block
}
Run Code Online (Sandbox Code Playgroud)
上面的代码也可以写成:
method(int useful, int _) {
// using '_' means I'm not going to use 2nd parameter in the block
}
Run Code Online (Sandbox Code Playgroud)
现在回答你的问题:
builder: (_, counter, __) => Translations(counter.value),
Run Code Online (Sandbox Code Playgroud)
意味着您有 3 个参数_, counterand __,并且只有counter您正在使用的参数,因此第一个和第三个参数用_and表示__。这只是编写代码的更简洁的方式。
| 归档时间: |
|
| 查看次数: |
2297 次 |
| 最近记录: |