context.select isn't defined for BuildContext

Viewed 10850

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(...);
  }
}
3 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.

Hi if using riverpod and get error for contect.read add this line

 import 'package:flutter_riverpod/flutter_riverpod.dart';

I was Using Bloc in VS Code and while call context.read I got this error. This error is because I haven't imported the bloc library. that's why I got this type of error. Make sure you have imported a relevant library. in My Case

import 'package:flutter_bloc/flutter_bloc.dart';
Related