Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

context.select isn't defined for BuildContext

Tags:

flutter

dart

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(...);
  }
}
like image 659
Rianou Avatar asked Oct 28 '20 15:10

Rianou


People also ask

Is the build context of a widget the same as its context?

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.

What is buildcontext in statelesswidget?

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.

Why context read is not allowed inside a build?

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:

What is the use of build context in Android?

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.


1 Answers

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.

like image 109
easeccy Avatar answered Sep 21 '22 13:09

easeccy