When reading dart code I often see some functions called with just an underscore _ parameter. It's bugging me out for some time now and since flutter has improved its analysis messages I have some clues... but I feel like I don't really grasp this concept :-(
Yesterday I wrote the following for a test :
when(mockDevice.getLocalPath()).thenAnswer(() async => fileFolder);
and obtain the following analysis
error: The argument type 'Future Function()' can't be assigned to the parameter type 'Future Function(Invocation)'.
When adding underscore it's working perfectly.
when(mockDevice.getLocalPath()).thenAnswer((_) async => fileFolder);
The most frightenning example I meet come from provider package written by @remi rousselet
builder: (_, counter, __) => Translations(counter.value),
It's from the provider example :
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';
}
Dart uses a leading underscore in an identifier to mark members and top-level declarations as private. This trains users to associate a leading underscore with one of those kinds of declarations. They see “_” and think “private”.
If an identifier starts with an underscore (_), it's private to its library. For details, see Libraries and visibility. Show activity on this post. Private fields also have the advantage that Lint can identify which fields were declared/instantiated and not used, which helps identify human errors.
Dart function is a set of codes that together perform a specific task. It is used to break the large code into smaller modules and reuse it when needed. Functions make the program more readable and easy to debug. It improves the modular approach and enhances the code reusability.
Underscore is normally an indication that you are not going to use that parameter inside the block it is just a good way to write code, for instance:
method(int useful, int useless) {
// say I am only going to use 'useful' in this block
}
Above code can also be written as:
method(int useful, int _) {
// using '_' means I'm not going to use 2nd parameter in the block
}
Answer to your question now:
builder: (_, counter, __) => Translations(counter.value),
means you have 3 parameters _
, counter
and __
, and only counter
is what you are using, so 1st and 3rd parameters are denoted with _
and __
. This is just cleaner way to write code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With