Reputation: 5
I consistently see code such as the following in Flutter example code:
sharedPreferencesService: context.read()
I understand that this must be a syntactical shortcut for
sharedPreferencesService: context<SharedPreferenceService>.read(),
Where is this feature of Dart documented?
Upvotes: 0
Views: 40
Reputation: 26
This feature is made possible by extension methods in Dart, which were introduced in version 2.7. In packages like provider, an extension method (for example, read()) is defined on the BuildContext. This allows you to use a syntax like:
sharedPreferencesService: context.read()
This is essentially a syntactical shortcut where the generic type is inferred, similar to explicitly writing:
sharedPreferencesService: context.read<SharedPreferenceService>()
For more detailed information, you can refer to the following documentation: Extension Methods – Dart Language Tour Generics – Dart Language Tour
Upvotes: 0
Reputation: 1105
It is called type inference in the Dart language.
What’s happening here is that the analyzer can infer the type of the generic based on the parameter type.
You can find more examples and explanations about it here:
https://dart.dev/language/type-system#type-inference
Upvotes: 0