unable to immediately consume a cubit after providing it in flutter_bloc

Issue

I am using flutter_bloc and cubits for my flutter app’s state, I am new to the whole bloc architecture but I understand the fundamentals, My problem is, I don’t want to wrap my entire App’s root with a Provider,
since the state will only be consumed once in a widget which is much deeper in the tree, but can be modifiable from it’s further children,

I am trying to use the BlocProvider to pass in the cubit to the context, and consume it immediately, instead of separating it out into another stateless widget,

BlocProvider(
            create: (BuildContext context) => SearchResultsCubit(),
            child: ListView.builder(
                itemCount:
                    BlocProvider.of<SearchResultsCubit>(context).state.length,

in the itemCount, I’m trying to access the state which is being provided by the BlocProvider immediately above it, but it doesn’t seem to work.

The app will throw an error saying it cannot locate the said Provider,
I would appreciate it if anyone could point out where I have gone wrong or what other approach I can use to achieve this result

thank you.

Solution

friend. You can try this construction.
Of course, you should implement your Cubit.

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: BlocProvider(
      create: (context) => SearchResultsCubit(),
      child: SecondPage(),
    ));
  }
}

class SecondPage extends StatelessWidget {
  const SecondPage({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<SearchResultsCubit, SearchResultsState>(
      builder: (context, state) {
        return Container(
          width: double.infinity,
          height: 100.0,
          child: ListView.builder(
            scrollDirection: Axis.horizontal,
            itemBuilder: (context, index) => Container(
                width: 50.0,
                height: 100.0,
                child: Center(child: Text(state[index].text))),
            itemCount: state.length,
          ),
        );
      },
    );
  }
}

Answered By – alexkolykhalov

Answer Checked By – Terry (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *