Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does it mean to pass `_` (i.e., underscore) as the sole parameter to a Dart language function?

Tags:

syntax

dart

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.

like image 411
Ethan Avatar asked Aug 27 '14 00:08

Ethan


People also ask

How do you define a function in darts?

Functions are the building blocks of readable, maintainable, and reusable code. A function is a set of statements to perform a specific task. Functions organize the program into logical blocks of code. Once defined, functions may be called to access code.


2 Answers

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.

DON’T use a leading underscore for identifiers that aren’t private.

Exception: An unused parameter can be named _, __, ___, etc. This happens in things like callbacks where you are passed a value but you don’t need to use it. Giving it a name that consists solely of underscores is the idiomatic way to indicate the value isn’t used.

https://dart.dev/guides/language/effective-dart/style

like image 164
Zectbumo Avatar answered Oct 02 '22 00:10

Zectbumo


An underscore (_) is usually an indication that you will not be using this parameter within the block. This is just a neat way to write code.

Let's say I've a method with two parameters useful and useless and I'm not using useless in the code block:

void method(int useful, int useless) {   print(useful); } 

Since useless variable won't be used, I should rather write the above code as:

void method(int useful, int _) { // 'useless' is replaced with '_'   print(useful); } 
like image 28
CopsOnRoad Avatar answered Oct 01 '22 22:10

CopsOnRoad