Error: Could not find the correct Provider above this StudentsList Widget
Trying to access the data from the provider package but stuck with this error I tried adding ChangeNotifierProvider to the main dart file but still getting the same error.
Home Screen
class HomeScreen extends StatelessWidget {
const HomeScreen({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
ChangeNotifierProvider(
create: (_) => Students(),
);
return Scaffold(
appBar: AppBar(
title: const Text("Home"),
),
body: StudentsList(),
);
}
}
StudentsList File
class StudentsList extends StatelessWidget {
@override
Widget build(BuildContext context) {
var studentDataList = Provider.of<Students>(context).studentsList;
return ListView.builder(
itemBuilder: (ctx, item) {
return ListTile(...);
}
}
CodePudding user response:
Moving Provider up to a parent, MaterialApp context, allows both Screen A and B to inherit its state/context.
provider(MaterialApp)
Screen A Screen B
check this link : Could not find the correct provider above this widget
and its good to check this link for more details : https://flutteragency.com/how-to-resolve-could-not-find-the-correct-provider-above-widget-in-flutter/
CodePudding user response:
Its just a syntax error that is creating this issue. Edited the code in the home screen to :
Widget build(BuildContext context) {
return ChangeNotifierProvider(
create: (_) => Students(),
child: Scaffold(
appBar: AppBar(
title: const Text("Home"),
),
body: StudentsList(),
),
);
}
}