Search code examples
flutterdartflutter-provider

Could not find the correct Provider above this ListView Widget


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

Solution

  • 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(),
          ),
        );
      }
    }