4

The variable/function name starts with underscore "_" means that it is a private variable/function in Dart language. It is well-known.

What if the underscore variable is used inside a function?

Is it necessary to use declare an underscored variable in a function(not in a class) to denote that the variable is only used in the function? or as it is self-evident that the declared variable can only be used in the function so that using underscore prefix is just a redundant thing? (or for the naming convention?) (when the function does not have any inner-function)

With underscore:

void sample() {
 var _something = getSomething();
 doSomethingWith(_something);
 //use _something
}

Without underscore:

void sample() {
 var something = getSomething();
 doSomethingWith(something);
 //use something
}

Plus, is there any performance-related difference between them?

klados
  • 706
  • 11
  • 33

2 Answers2

6

What if the underscore variable is used inside a function?

Dart's official style guide expressly advises against doing that (emphasis mine):

There is no concept of “private” for local variables, parameters, or library prefixes. When one of those has a name that starts with an underscore, it sends a confusing signal to the reader. To avoid that, don’t use leading underscores in those names.

As for the other question in your post:

Is it necessary to use declare an underscored variable in a function(not in a class) to denote that the variable is only used in the function?

No, all variables declared inside a function are naturally limited in-scope to that function. Adding an annotation to say a local is "private" is both redundant and incorrect (as locals aren't "private" because locals aren't shared).

void sample() {
 var _something = getSomething();
 doSomethingWith(_something);
 //use _something
}

In this example, _something is not actually "shared" because doSomethingWith is passed a copy of _something: it doesn't have a reference or pointer to _something.

Dai
  • 141,631
  • 28
  • 261
  • 374
1

Dai is right about almost everything but I want to correct him. Primitives (like int, bool, and num) are passed by value. Objects are passed by reference. So doSomethingWith will have reference to _something if _something is not a primitive But it doesn't change the answer. You don't need to underscore variables in methods.

  • 1
    Dart uses reference-passed-by-value. Dart doesn’t support “true” (I.e. C++-style) references nor can you pass-by-ref in Dart either, annoyingly. (This QA refers to Java, but the same concept applies to Dart: https://stackoverflow.com/q/40480/159145 ) – Dai Aug 02 '22 at 18:53