flutter - 如何在不使用任何库的情况下在flutter中使用bloc

标签 flutter dart bloc flutter-state

我想使用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/

相关文章:

list - 从 ListView.builder Flutter 中删除项目

收到新事件时,Flutter Bloc 取消正在运行的事件

flutter -- 创建移动应用程序时对象创建顺序是什么?

flutter - Flutter 中的替代库类似于 iOS 中的可达性?

flutter - 如何在 flutter 中绘制自定义形状并拖动该形状?

flutter - Riverpod,在 BuildContext 和 Provider 之外读取状态

Flutter BLOC 和 Provider 如何一起注册

rest - 从json调用解析以在flutter中映射

flutter - 使用flutter选择时如何通过更改颜色和大小来创建圆形按钮

dart - 如何在 flutter 中绘制自定义形状