跳到主要内容

dart flutter中函数参数(_)

管

管理员

https://stackoverflow.com/questions/25517016/what-does-it-mean-to-pass-i-e-underscore-as-the-sole-parameter-to-a-dart

2020年09月23日 2,618 次阅读
本页目录

问题1:I'm learning Dart and see the following idiom a lot:

someFuture.then((_) => someFunc());

I have also seen code like:

someOtherFuture.then(() => someOtherFunc());

Is there a functional difference between these two examples? A.k.a., What does passing _ as a parameter to a Dart function do?

This is particularly confusing given Dart's use of _ as a prefix for declaring private functions.

It's a variable named _ typically because you plan to not use it and throw it away. For example you can use the name x or foo instead. The difference between (_) and () is simple in that one function takes an argument and the other doesn't. 

 问题2:So, the function being called expects a parameter, and the code is passing junk (an unassigned variable)? Why not use null, for clarity? Just to save typing? And, won't the function be a little surprised when it tries to use the unassigned, untyped variable? Or, am I missing something?

It's not passing junk, it's just not being used. 2) null is a keyword and can't be used as a variable name. 3) Yes, It saves typing and also gives a low profile look. 4) No, _ is an assigned variable. No surprises here.



 

Related

相关文章

同分类文章 →
2026年10月31日 flutter

`auth()->id()` 到底返回谁?Sanctum 多态令牌与双会员系统的踩坑记录

## 引子先看一段看起来很正常的代码:```php$userId = auth('sanctum')->id();if ($userId) {    $res['isLiked'] = $this->likes()        ->where('user_id', $userId

2026年07月28日 flutter

Dart 3 记录(Records)和密封类(Sealed classes)

Dart 3 引入了几个极其强大的语言特性,其中最耀眼、对我们日常开发改变最大的就是 记录(Records) 和 密封类(Sealed classes),它们配合 模式匹配(Pattern Matching),让 Dart 的表现力达到了现代编程语言(如 Swift、Kotlin、Rust

2026年06月29日 flutter

flutter的 Clean Architecture架构设计

Clean Architecture(清晰架构)是一种将应用程序分层的设计模式,强调关注点分离与依赖规则,通过将业务逻辑与框架、UI、数据源解耦,提升代码的可测试性、可维护性与可扩展性。在 Flutter/Dart 环境下,Clean Architecture 通

WeChat

扫码加我微信

微信二维码