5

In short, does the context belong in the BLoC class and if it doesn't, what's the right approach?

I'm using a Provider as an abstraction layer between the Firebase DB and the UI. Recently, we've been abstracting further away to use the BLoC pattern, so that the widgets don't manipulate the data in the Provider directly. It's all proceeding nicely, but due to the fact that we use both the providers and the BLoC, I am not sure how to use the BuildContext properly, as the context ha more to do with the Widgets/UI than the business logic.

Here's an example:

class SomeWidget extends StatelessWidget {
  final SomeWidgetBloc bloc;
  
  SomeWidget({Key key, this.bloc});
  
  @override
  Widget build(BuildContext context) => StreamBuilder(stream: bloc.getSomeData, 
     builder: (context, snapshot) {
        return Text(snapshot.data ?? "Empty");
     }
}

class SomeWidgetBloc {
  BuildContext context; // should it be here? Currently, it's needed for the Provider
  
  SomeWidgetBloc(BuildContext context);
  
  Stream<String> get getSomeData {
     return Provider.of<SomeFirebaseProvider>(context).fetchSomeData();
  } 
}
Dmitri Borohhov
  • 1,513
  • 2
  • 17
  • 33
  • keep context in bloc classes is really bad idea –  Dec 01 '20 at 12:03
  • 1
    This is the bad part of the provider, you need the context for everything, your "presenter" or bloc should not contain the context of your view. That is why git_It is a better option for Service Locator. – Luiz Filipe Medeira Dec 01 '20 at 12:39
  • use https://pub.dev/packages/injectable/ It is one of the best options for DI. Don't use plain get_it – Ilya Maximencko Dec 01 '20 at 13:36
  • injectable is overcomplicated and redundant, just use plain getit –  Dec 02 '20 at 05:32

1 Answers1

0

You should pass your SomeFirebaseProvider instance to the SomeWidgetBloc constructor at creation time.