I have created the Cubit SurveysCubit
in HomePage
from BlocProvider
component, now, I want to access it from a new page pushed in its child body.
All works fine until the pushed page is reached here the following error is shown telling me that the SurveysBloc
created on the previous page is not found :
BlocProvider.of() called with a context that does not contain a SurveysCubit.
This is the home page :
class HomePage extends StatelessWidget {
const HomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (_) =>
SurveysCubit(repo: RepositoryProvider.of<SurveyRepository>(_)),
child: Builder(builder: (newContext) {
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(
onPressed: () => Navigator.push(
newContext,
MaterialPageRoute<void>(
builder: (BuildContext newContext) => Surveys(),
),
),
child: const Text("Surveys"),
),
],
),
),
);
}),
);
}
}
Surveys
, the pushed page :
class Surveys extends StatelessWidget {
List<Survey> surveys = [];
Surveys({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
surveys = BlocProvider.of<SurveysCubit>(context).getSurveys; //this call fails
return Scaffold(
body: ListView.builder(
itemCount: surveys.length,
itemBuilder: (context, i) => Column(
children: [
ShowSurvey(survey: surveys[i]),
SizedBox(
height: 20,
),
],
),
),
);
}
}
I know I could avoid Builder
widget, but I wanted to force a new context creation. I think I provided the right context
, so it should work, I don't understand what's happening.