Why I can't use any extension methods of Provider (context.select
, context.read
and context.listen
)?
I get a static error like this.
The method 'select' isn't defined for the type 'BuildContext'.Try correcting the name to the name of an existing method, or defining a method named 'select'..
class MyWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
// Following line causes the problem
var isFavorite = context.select<FavModel, bool>(
(fav) => fav.items.contains(item),
);
return OtherWidget(...);
}
}
In particular, this means that within a build method, the build context of the widget of the build method is not the same as the build context of the widgets returned by that build method. This can lead to some tricky cases. For example, Theme.of (context) looks for the nearest enclosing Theme of the given build context.
A handle to the location of a widget in the widget tree. This class presents a set of methods that can be used from StatelessWidget.build methods and from methods on State objects. BuildContext objects are passed to WidgetBuilder functions (such as StatelessWidget.build ), and are available from the State.context member.
Provider.of is allowed in build for backward-compatibility. Overall, the reasoning behind why context.read is not allowed inside build is explained in its documentation: DON'T call [read] inside build if the value is used only for events:
BuildContext objects are passed to WidgetBuilder functions (such as StatelessWidget.build ), and are available from the State.context member. Some static functions (e.g. showDialog, Theme.of, and so forth) also take build contexts so that they can act on behalf of the calling widget, or obtain data specifically for the given context.
context.select
, context.read
and context.listen
are extension methods from Provider. To use them you should import Provider.
Add this on top of your file:
import 'package:provider/provider.dart';
It should be auto-imported by default. It's a known issue.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With