5

I have a class called A which is a Stateless class and I have a class called B which is a Stateful class

The build method of A class is as follows

@override
  Widget build(BuildContext context) {
    return BlocProvider(
      bloc: DashboardListBloc(),
      child: Scaffold(
          body: SingleChildScrollView(
        child: Column(
          children: <Widget>[
            SafeArea(child: _dashboardAppBar(context)),
            SizedBox(
              height: 10.0,
            ),
            B() // this is class B
          ],
        ),
      )),
    );

I have declared my bloc object in B class Suppose in body of class A, i wrap SingleChildScrollView with RefreshIndicator, so how in its refresh property i am supposed to call the methods of Bloc class whose reference are defined in class B.

I thought of moving everything to class B and removing class A but that causes another problem as i have to initialise Bloc in init method and as init is called before build, bloc will always result in null as i will be using BlocProvider InheritedWidget in build method of class B

1 Answers1

0

You should create one single bloc instance and provide it to both classes. In other words your bloc should not be created in class B but instead you can create your bloc by wrapping any common parent of A and B (such as your App widget) with a BlocProvider and using the create method. Then in any child widget you can do BlocProvider.of<MyBloc>() or context.read<MyBloc>() and this way both classes A and B will share the same Bloc instance.

Hadi Hassan
  • 331
  • 1
  • 3