gpt4 book ai didi

Flutter-Firestore Bloc

转载 作者:IT王子 更新时间:2023-10-29 07:06:06 30 4
gpt4 key购买 nike

我想知道如何为 Firestore 实现 Bloc 模式。
当从 flutter 默认应用程序应用 Bloc 增量应用程序时,看起来像这样。

class IncrementBloc implements BlocBase {

int _counter;


StreamController<int> _counterController = StreamController<int>();
StreamSink<int> get _inAdd => _counterController.sink;
Stream<int> get outCounter => _counterController.stream;


StreamController<int> _actionController = StreamController<int>();
StreamSink<int> get incrementCounter => _actionController.sink;

IncrementBloc() {
_counter = 0;
_actionController.stream.listen(_handleLogic);
}

void _handleLogic(data) {
_counter += 1;
_inAdd.add(_counter);
}

@override
void dispose() {
_counterController.close();
_actionController.close();
}
}

问题是如何为 Firestore 实现这个逻辑。例如,如果我想在用户获得新关注者时更新徽章值,我必须监听 Firestore 文档的新创建。但我不知道如何创建涵盖这些内容的 Bloc Firestore 版本,我找不到它。我如何在 Bloc 中收听谁能告诉我如何创建它?

最佳答案

像下面这样的东西应该适合你,只需在你想要显示该值的页面上添加监听器

class IncrementBloc implements BlocBase {

int _counter;

StreamController<int> _counterController = StreamController<int>();
StreamSink<int> get _inAdd => _counterController.sink;
Stream<int> get outCounter => _counterController.stream;


StreamController<int> _actionController = StreamController<int>();
StreamSink<int> get incrementCounter => _actionController.sink;

IncrementBloc() {
// Get the latest value from firebase and listen to stream
countAPI.getNumber().then(number) {
_counter = number;
_inAdd(_counter);
});
_actionController.stream.listen(_handleLogic);
}

void _handleLogic(data) async {
_counter += 1;
await countAPI.updateNumber(_counter); // this updates firebase
}

@override
void dispose() {
_counterController.close();
_actionController.close();
}
}

class APIs {
Future<int> getNumber() async {
try {
// Get number from firebase
} catch (e) {
// Error
}
}

Future<void> updateNumber() async {
// Firebase upload
}
}

APIs countAPI = APIs();

关于Flutter-Firestore Bloc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52523580/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com