Issue
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';
}
Solution
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.
Answered By - CopsOnRoad
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.