0
votes

I've recently started playing with BLoC pattern in Flutter and am struggling to understand an issue with the BLoC provider. My class looks like this

class LoginBlocProvider extends InheritedWidget {
  final LoginBloc bloc;

  LoginBlocProvider({Key key, Widget child})
      : bloc = LoginBloc(),
        super(key: key, child: child);

  @override
  bool updateShouldNotify(InheritedWidget oldWidget) => true;

  static LoginBloc of(BuildContext context) {
    return context.dependOnInheritedWidgetOfExactType<LoginBlocProvider>().bloc;
  }
}

Now most of the articles I've read say to add the Provider to the widget tree right above the Material app

return LoginBlocProvider(
    child: MaterialApp(...)
)

My issue with this is what happens if you have a complex app with a large number of screens. It seems this would get messy really quickly

return LoginBlocProvider(
  child: AccountBlocProvider(
    child: ScreenOne(
      child: ScreenTwo(
        child: ScreenThree(
          ...
        )
      )
    )
  )
)

Is there more efficient way to manage this?

1

1 Answers

1
votes

This page explains how to get around the readability issue of providing all of your blocs at the start of the application. There is a Widget called MultiBlocProvider that takes a list of Provider widgets.

So it would look like this:

return MultiBlocProvider(
  providers: [
    BlocProvider<LoginBloc>(
      create: (BuildContext context) => LoginBloc(),
    ),
    BlocProvider<AccountBloc>(
      create: (BuildContext context) => AccountBloc(),
    ),
    BlocProvider<PageOneBloc>(
      create: (BuildContext context) => PageOneBloc(),
    ),
  ],
  child: MaterialApp(...)
)