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?
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?
Share Improve this question asked Feb 1 at 12:19 Koorb NotsyorKoorb Notsyor 152 bronze badges 2 |2 Answers
Reset to default 0This 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
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
SharedPreferenceService
? – Md. Yeasin Sheikh Commented Feb 1 at 12:24context
is a variable; variables do not have type parameters;context<SharedPreferenceService>
would not be valid syntax. Generic type arguments are applied to generic types (classes andtypedef
s) or to generic functions. – jamesdlin Commented Feb 1 at 18:12