I am getting the following error when using Provider in a WebApp. I've seen this before when creating none webapps and can usually fix it. However I can't see where the error is within the webapp. I am creating the MultiProvider in Main.dart and above the MaterialApp widget. Here is the error:
Error: Could not find the correct Provider<List> above this CategoryWidget Widget
This happens because you used a BuildContext
that does not include the provider
of your choice.
And my MultiProvider code:
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return FutureBuilder(
future: Firebase.initializeApp(),
builder: (context, snapshot) {
// Check for errors
if (snapshot.hasError) {
return MaterialApp(
home: Scaffold(
body: Container(
alignment: Alignment.center,
child: const Text('ERROR: DID NOT INITIALIZE FIREBASE!')),
),
);
}
if (snapshot.connectionState == ConnectionState.done) {
print("FIREBASE INITIALIZED");
final catCollection = FirebaseFirestore.instance
.collection('categories')
.orderBy("active", descending: true);
final categories = catCollection.snapshots().map((snapShot) =>
snapShot.docs
.map((catDoc) => Category.fromMap(catDoc.data(), catDoc.id))
.toList());
return MultiProvider(
providers: [
StreamProvider<User?>(
create: (_) => FirebaseAuth.instance.authStateChanges(),
initialData: null,
),
StreamProvider<List<Category?>>(
create: (_) => categories,
initialData: [],
),
ChangeNotifierProvider.value(
value: Categories(),
),
ChangeNotifierProvider.value(
value: Auth(),
),
],
child: MaterialApp(
title: "Qi Gang's Dashboard",
debugShowCheckedModeBanner: false,
// home: LoginSignupScreen(isLoginForm: true),
initialRoute: LoginSignupScreen.id,
routes: {
LoginSignupScreen.id: (context) =>
LoginSignupScreen(isLoginForm: true),
MainScaffold.id: (context) => MainScaffold(),
And lower down the widget tree, called from MainScaffold is my CategoryWidget, where the error is occurring:
Widget categoryGrid(BuildContext context) {
final categories = Provider.of<List<Category>>(context);
Been trying to solve this for some time now and am blocked so would really appreciate it if you could point out where I am going wrong here.
Many thanks
CodePudding user response:
As you can read in providers official documentation. here
context.watch<T>(), which makes the widget listen to changes on T
context.read<T>(), which returns T without listening to it
context.select<T, R>(R cb(T value)), which allows a widget to listen to only a small part of T.
These methods will look up in the widget tree starting from the widget associated with the BuildContext passed and will return the nearest variable of type T
found (or throw if nothing is found).
and in your code you are defining <List<Category?>>
in provider and you are Looking for <List<Category>>
down the widget tree thus this is giving you error.
CodePudding user response:
You need to add provider (or initialize) to main.dart and then try to use it. It will work surely.