我想使用bloc pattern
管理我的应用程序的状态,我已经在互联网上搜索并找到了很多主题,但是所有人都不想使用third party libraries
。
那么,有没有资源或示例可以帮助我们使用bloc pattern
而不依赖于任何外部库,例如:bloc, flutter_bloc, rxdart
?
我只想使用flutter built-in
功能,而不要使用任何其他库。
最佳答案
这是我的旧代码的摘录,但是我强烈建议使用bloc和flutter_bloc,它删除了许多样板代码,它更安全,也更广为人知,VSCode插件也可以处理很多代码生成。
class VotesBloc {
final List<VoteCount> voteGroups = []; // initial state
// broadcasting stream so it can be used multiple times
final _controlStateController = StreamController<List<VoteCount>>.broadcast();
StreamSink<List<VoteCount>> get _incomingVote => _controlStateController.sink;
Stream<List<VoteCount>> get outgoingVote => _controlStateController.stream;
final _votesEventController = StreamController<VoteEvent>.broadcast();
Sink<VoteEvent> get votesEventSink => _votesEventController.sink;
VotesBloc() {
_votesEventController.stream.listen(_mapValuesToState);
}
void _mapValuesToState(VoteEvent event) {
if (event is NewVoteEvent) {
// handle this state
} else if (event is VoteChangedEvent) {
// handle this state
}
_incomingVote.add(voteGroups);
}
void dispose() {
_controlStateController.close();
_votesEventController.close();
}
}
abstract class VoteEvent {
final Vote _vote;
VoteEvent(this._vote);
}
class NewVoteEvent extends VoteEvent {
NewVoteEvent(Vote vote) : super(vote);
}
class VoteChangedEvent extends VoteEvent {
VoteChangedEvent(Vote vote) : super(vote);
}
class VoteCount {
final String value;
int counter;
List<Vote> votes;
VoteCount(this.value, {this.counter, this.votes});
}
和生成器功能:
StreamBuilder<List<VoteCount>>(
stream: votesBloc.outgoingVote,
initialData: votesBloc.voteGroups,
builder: (BuildContext context, AsyncSnapshot<List<VoteCount>> snapshot) {
return Widget();
}
)
在外面使用集团:
votesBloc.votesEventSink.add(VoteChangedEvent(vote));
关于flutter - 如何在不使用任何库的情况下在flutter中使用bloc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61915411/