我正在尝试正确使用 bloc 模式,但是找不到正确使用getter的任何好的示例。我所追求的只是一个流,而是一种基于参数等从我的商店返回经过过滤的数据的方法。我不认为为此添加整个新流不是一个好主意,并且想弄清楚我正在执行的操作是否违反了最佳做法(尽管它的确起作用了)。
UI:
StreamBuilder(
stream: _bloc.stream,
initialData: _bloc.state.initialData,
builder: (BuildContext context, AsyncSnapshot<CounterState> snapshot) {
return Row(
children: <Widget>[
Text(snapshot.data.counter.toString()),
Text(snapshot.data.sayHi('Bob')),
],
);
},
),
集团:
import 'dart:async';
import 'package:flutter/cupertino.dart';
import './counter_event.dart';
import './counter_state.dart';
@immutable
class CounterBloc {
final state = new CounterState();
final _counterStateController = StreamController<CounterState>();
// Only expose the out
StreamSink<CounterState> get _inCounter => _counterStateController.sink;
Stream<CounterState> get stream => _counterStateController.stream;
// only expose the in
final _counterEventController = StreamController<CounterEvent>();
Sink<CounterEvent> get counterEventSink => _counterEventController.sink;
// listen to the output
CounterBloc() {
_counterEventController.stream.listen(_mapEventToState);
}
void _mapEventToState(CounterEvent event) {
final res = state.mapEventToState(event);
_inCounter.add(res);
}
void dispose() {
_counterStateController.close();
_counterEventController.close();
}
}
事件:
import 'package:flutter/cupertino.dart';
@immutable
abstract class CounterEvent {}
class IncrementEvent extends CounterEvent {}
class DecrementEvent extends CounterEvent {}
状态:
import 'counter_event.dart';
class CounterState {
int _counter = 0;
CounterState get initialData => this;
int get counter => _counter;
CounterState mapEventToState(CounterEvent event) {
if (event is IncrementEvent) {
_counter++;
} else if (event is DecrementEvent) {
_counter--;
}
print(_counter.toString());
return this; // @TODO - IS THIS OK ??
}
// @TODO - Is this the correct place for this to go? (filtering of _counter data)
String sayHi(String name) {
return 'HI $name ' + _counter.toString();
}
}