Flutter – How to architect multiple nested BLoC?

Issue

Suppose there is a top-level BLoC called PreferenceBloc, and inside that BLoC is another BLoC called PageBloc. If the logic inside PageBloc requires on a value stream from PreferenceBloc (i.e., create a new page needs to know page configuration now), how should I architect this?

Code sample:

class PreferencesBloc{
  final preferencesService=PreferencesService();

  // Output interfaces of Bloc
  ValueObservable<String> get mainDir => _mainDir.distinct().shareValue(seedValue: '/');
  final _mainDir = BehaviorSubject<String>(seedValue: '/');

  // Input interfaces of Bloc...
  // .........
}
class PageBloc{
  final List<PageInfo> _pageInfos=<PageInfo>[];
  // Output interfaces of Bloc...
  // .........

  // Input interfaces of Bloc...
  Sink<int> get pageCreation => _pageCreationController.sink;
  final _pageCreationController = StreamController<int>();

  pageBloc(){
    _pageCreationController.stream.listen(_handleCreation);
  }
  void _handleCreation(int pos){
    _pageInfo.insert(pos, PageInfo('I need the mainDir here!')); //Need info from PreferencesBloc!!!
  }
}

class PreferencesProvider extends InheritedWidget{
  final PreferencesBloc preferencesBloc;
  //...
}
class PageProvider extends InheritedWidget{
  final PageBloc pageBloc;
  //...
}



void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return PreferencesProvider(
      child: PageProvider(
        child: MaterialApp(
          home: Scaffold(
            body: Text("test"),
          ),
        ),
      ),
    );
  }
}

Edit: To sum up, it is convenient to communicate between Bloc and widget in flutter, but is there a good way to communicate between Bloc and Bloc?

Solution

This question was asked at Nov 18. Currently, there is already a great bloc library that support nested bloc. You can use https://pub.dartlang.org/packages/flutter_bloc in the official pub dart. So far, i have been using it for developing a quite complex app, and it is great.

Answered By – Haqqi

Answer Checked By – Cary Denson (FlutterFixes Admin)

Leave a Reply

Your email address will not be published.