本文介绍了如何在Flutter中使用bloc模式在UI上显示函数回调和错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

bloc.dart

class Bloc{
Bloc(){
additionalController.stream.listen(onAdd);
}

void dispose() async {
additionalController.close();
_itemAdd.close();
}

final additionalController = StreamController<Data>();
Sink<Data> get addItem => additionalController.sink;

Stream<String> get addGet => _itemAdd.stream;
final _itemAdd = BehaviorSubject<String>();

void onAdd(Data data) {
_addWork(data);
}

Future<Null> _addWork(Data data) async {

//work

}).whenComplete(() {

_itemAdd.add("complete work");

}).catchError((e) {
_itemAdd.addError("Error in Adding Data");
  });
 }
}

bloc 应该仅用于共享业务逻辑,但错误处理部分与业务逻辑无关。

As bloc should only be used and shared to handle the business logic, but the error handling part has nothing to do with the business logic.

如何在UI上显示回调和bloc错误。我不认为 StreamBuilder 是唯一的解决方案。

How to show callbacks and error of bloc on UI. I don't think StreamBuilder is the only solution.

如果我们使用 StreamBuilder ,这样,每次重建时我们都会向bloc重复发送回调,这毫无意义。

If we use StreamBuilder, In that way, We repetitively send callback to bloc every time rebuilding happens and this make no sense.

是否有正确的方法要这样做吗?

谢谢!

推荐答案

到目前为止,对我有用的是使用表示回调的接口。

What has worked for me so far, is using an interface that represents a callback.

abstract class AddItemDelegate {
  void onSuccess();
  void onError(String message);
}

然后在 bloc 如下:

class Bloc {
  AddItemDelegate _delegate;
  // ...
  Function addItem(Data item, AddItemDelegate delegate) => () {
    _delegate = delegate;
    additionalController.sink.add(item);
  }
  // ...
  Future<Null> _addWork(Data data) async {
    try {
      final work = await //work...
      _itemAdd.add("complete work");
      _delegate?.onSuccess();
    }
    catch(e) {
      final error = "Error in Adding Data";
      _itemAdd.addError(error);
      _delegate?.onError(error);
    }
  }
}

然后在 StatefulWidget (或 StatelessWidget ),您可以执行以下操作:

Then on your StatefulWidget (orStatelessWidget) you can do the following:

class MyWidget extends StatelessWidget implements AddItemDelegate {
  @override
  void onSuccess() {
    // e.g.: Show a dialog or navigate to other screen
  }

  @override
  void onError(String message) {
    // e.g.: Show an error dialog
  }

  @override
  Widget build(BuildContext context) {
    final bloc = // ...
    final data = // ...
    return MaterialButton(
        child: Text("Add Item"), 
        onPressed: bloc.addItem(data, this));
  }
}

这种方式可以在使用BLoC模式时使用回调。

This way one can use callbacks while using BLoC pattern.

这篇关于如何在Flutter中使用bloc模式在UI上显示函数回调和错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 01:00