IncorrectMouse
IncorrectMouse

Reputation: 209

flutter_bloc could not find the correct provider

I have a Cubit that fetches data from an API. I want to connect that to the UI so I added a BlocProvider on top of that widget at first. That gave me an error, so I wrapped the MaterialApp with the BlocProvider which gave the same error. After that, I tried to have it around the route I want to access it in with the same result.

MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: getThemeData(),
      onGenerateRoute: _router.generateRoutes,
      initialRoute: _store.get('users', defaultValue: {}).isEmpty
          ? '/onboarding'
          : '/dashboard',
);

routes.dart

final PANCubit _panCubit = PANCubit(PANRepository());
  Route<dynamic> generateRoutes(RouteSettings settings) {
    switch (settings.name) {
      // case '/':
      //   return MaterialPageRoute(builder: (context) => Home());
      case '/':
      case '/onboarding':
        return MaterialPageRoute(
          builder: (context) => BlocProvider.value(
            value: _panCubit,
            child: OnBoarding(),
          ),
        );
...

And I want to access that in the UI here:

OnBoardingView(
  imagePath: process_svg,
  titleWidget: BlocBuilder(
    builder: (context, state) {
      context.read<PANCubit>().getPANInformation(_panText.text);

      if (state is PANLoading) {
        return CircularProgressIndicator();
      } else if (state is PANFetched) {
        return Text(
          'Hey ${state.panInformation.fullName}!',
          style: Theme.of(context).textTheme.headline1,
        );
      } else {
        return Text('Hmmm..Something went wrong.');
      }
    },
  ),
...

Upvotes: 0

Views: 825

Answers (1)

Augustin R
Augustin R

Reputation: 7799

You need to precise which bloc you want to access in BlocBuilder :

titleWidget: BlocBuilder<PANCubit, PANState>( // Replace PANState by the type of state
    builder: (context, state) {
      state.getPANInformation(_panText.text);

      if (state is PANLoading) {
        return CircularProgressIndicator();
      } else if (state is PANFetched) {
        return Text(
          'Hey ${state.panInformation.fullName}!',
          style: Theme.of(context).textTheme.headline1,
        );
      } else {
        return Text('Hmmm..Something went wrong.');
      }
    },
  ),

Upvotes: 1

Related Questions