最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

dart - Flutter use of variable <T> : context.read() instead of context<T>.read() - Stack Overflow

programmeradmin1浏览0评论

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
  • what are you using for SharedPreferenceService ? – Md. Yeasin Sheikh Commented Feb 1 at 12:24
  • There is no shorthand being done in this particular example. context 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 and typedefs) or to generic functions. – jamesdlin Commented Feb 1 at 18:12
Add a comment  | 

2 Answers 2

Reset to default 0

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

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

发布评论

评论列表(0)

  1. 暂无评论