BuildContext in a Flutter BLoC class

Viewed 621

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();
  } 
}
1 Answers

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

Related