I have implemented a countetEvent and counterBloc:
abstract class CounterEvent {}
class IncrementEvent extends CounterEvent {}
class DecrementEvent extends CounterEvent {}
and counterBloc:
import 'dart:async';
import 'counter_event.dart';
class CounterBloc {
int _counter = 0;
final _counterStateController = StreamController<int>();
StreamSink<int> get _inCounter => _counterStateController.sink;
Stream<int> get counter => _counterStateController.stream;
final _counterEventController = StreamController<CounterEvent>();
Sink<CounterEvent> get counterEventSink => _counterEventController.sink;
CounterBloc() {
_counterEventController.stream.listen(_mapEventToState);
}
void _mapEventToState(CounterEvent event) {
if (event is IncrementEvent)
_counter++;
else
_counter--;
_inCounter.add(_counter);
}
void dispose() {
_counterStateController.close();
_counterEventController.close();
}
}
and in My main.dart I have declared:
final _bloc = CounterBloc();
I have two buttons one to increment and one for drecrement. the decrement works just find when using it in the main.dart file like soo:
RaisedButton(
onPressed: () =>
_bloc.counterEventSink.add(DecrementEvent()),
child: Text("Minus"),
)
This will update the variable in the bloc and also the widget. But for the increment, when I call it from outside of the main.dart with a function it increment the value in the bloc but the UI doesn't update. This is how I implement it:
children: [
Button(), /// A stateful widget that returns a button
RaisedButton(
onPressed: () =>
_bloc.counterEventSink.add(DecrementEvent()),
child: Text("Minus"),
),
],
This is the button class:
class Button extends StatefulWidget {
@override
_ButtonState createState() => _ButtonState();
}
class _ButtonState extends State<Button> {
final _bloc = CounterBloc();
@override
Widget build(BuildContext context) {
return Container(
child: RaisedButton(
onPressed: () => _bloc.counterEventSink.add(IncrementEvent()),
child: Text("Add"),
),
);
}
}
How can I use the bloc events outside of the widget and update the UI? Or simply put, how can I update a stateful widget from another class.
This solution of mine might answer your question. That's how I solved some communication issues between different blocks. You can also look-up inherited widgets, however, I haven't tried this, yet.