Home:ALL Converter>Flutter - How to architect multiple nested BLoC?

Flutter - How to architect multiple nested BLoC?

Ask Time:2018-11-18T15:52:06         Author:First_Strike

Json Formatter

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?

Author:First_Strike,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/53358894/flutter-how-to-architect-multiple-nested-bloc
yy