Getting:
Error: Could not find the correct Provider<TheState> above this Consumer<TheState> Widget
Wondering why? Thank you
Main:
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
runApp(const MyHomePage(
title: 'ok',
));
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
void initState() {
super.initState();
WidgetsBinding.instance?.addPostFrameCallback((_) {
var state = Provider.of<TheState>(context, listen: false);
state.initItems();
});
}
@override
Widget build(BuildContext context) {
return DogList();
}
}
class DogList extends StatelessWidget {
@override
Widget build(BuildContext context) {
//ERROR IS LINE BELOW
return Consumer<TheState>(builder: (context, state, child) {
var prod = state.getItems();
return DogApp();
});
}
}
class DogApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return SizedBox(height: 500, width: 500, child: Text("ok"));
}
}
TheState.dart
import 'package:firebase_database/firebase_database.dart';
import 'package:flutter/material.dart';
class TheState extends ChangeNotifier {
int? items;
Query? _feedQuery;
final DatabaseReference kDb = FirebaseDatabase.instance.ref();
Future<bool> dbInit() {
try {
_feedQuery!.onChildAdded.listen(_childAdded);
initItems();
return Future.value(true);
} catch (error) {
print("ERROR");
return Future.value(false);
}
}
int? getItems() {
return items;
}
void initItems() {
var calledFrom = "getItems";
try {
print("in try" " " calledFrom);
kDb.child('item').once().then((DatabaseEvent event) {
print("returned" " " calledFrom);
final snapshot = event.snapshot;
if (snapshot.value != null) {
var map = snapshot.value as Map<dynamic, dynamic>;
items = map.length;
}
}).catchError((e, stackTrace) {
print("in catchError" " " calledFrom);
}).whenComplete(() => print("COMPLETE" " " calledFrom));
} catch (error) {
print("catch" " " calledFrom);
} finally {
print("finally" " " calledFrom);
}
}
void _childAdded(DatabaseEvent event) {}
}
CodePudding user response:
As the error states: you need to create provider somewhere above in the widget tree.
ChangeNotifierProvider(
create: (_) => TheState(),
child: //the rest of the tree of your app here
)
Take a look at the examples here