flutterdartsyntax

Flutter use of variable <T> : context.read() instead of context<T>.read()


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?


Solution

  • 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