I'm new on Dart and i want o undertand this BLoC pattern, so I made this class to implement this pattern:
generic class with a mapping of behaviors passed on constructor:
import 'dart:async';
class BlocPattern<I, O> {
//
BlocPattern(Map<I, O Function(I)> behavior) {
_widget2Bloc.stream.listen((event) {
if (behavior.keys.contains(event)) {
_bloc2Widget.sink.add(behavior[event]!(event));
} else {
_bloc2Widget.sink.addError(
Exception('missing mapping on BLoC pattern: event=($event)'));
}
});
}
final StreamController _widget2Bloc = StreamController<I>();
final StreamController _bloc2Widget = StreamController<O>();
void add(I input) => _widget2Bloc.sink.add(input);
Stream<O> get stream => _bloc2Widget.stream as Stream<O>;
}
One example of use of this class is:
Map<String, String Function(String c)> behavior = {
"foo": (String s) => "Is this a valid implementation?",
"bar": (String s) => "Can you guys tell me your opinion?",
};
//declaring
BlocPattern b2 = BlocPattern<String, String>(behavior);
//send some action
b2.add("foo");
b2.add("bar");
//an then you can listen to this on another place:
b2.stream.listen((e) => print("result: $e"));
on the terminal we get:
Restarted application in 222ms.
result: Is this a valid implementation?
result: Can you guys tell me your opinion?