如何使用StreamBuilder管理集团抛出的异常?

时间:2019-06-20 12:28:39

标签: flutter dart dart-http

当提供者在http.get()调用期间遇到问题时,我正在尝试将快照错误状态返回给StreamBuilder。就我而言,当http.get()返回不同于200的状态(确定)时,我抛出异常。 我希望能够将错误状态返回快照并针对这种情况执行特定的代码。 现在,当我引发异常时,应用程序便崩溃了。

提供者:

class FmsApiProvider {
  Future<List<FmsListResponse>> fetchFmsList() async {
    print("Starting fetch FMS..");
    final Response response = await httpGet('fms');
    if (response.statusCode == HttpStatus.ok) {
      // If the call to the server was successful, parse the JSON
      return fmsListResponseFromJson(response.body);
    } else {
      // If that call was not successful, throw an error.
      //return Future.error(List<FmsListResponse>());
      throw Exception('Failed to load FMSs');
    }
  }
}

存储库:

class Repository {
  final fmsApiProvider = FmsApiProvider();

  Future<List<FmsListResponse>> fetchAllFms() => fmsApiProvider.fetchFmsList();
}

集团:

class FmsBloc {
  final _fmsRepository = Repository();

  final _fmsFetcher = PublishSubject<List<FmsListResponse>>();

  Observable<List<FmsListResponse>> get allFms => _fmsFetcher.stream;

  fetchAllFms() async {
    List<FmsListResponse> itemModel = await _fmsRepository.fetchAllFms();
    _fmsFetcher.sink.add(itemModel);
  }

  dispose() {
    _fmsFetcher.close();
  }
}

我的StreamBuilder:

StreamBuilder(
            stream: bloc.allFms,
            builder: (context, AsyncSnapshot<List<FmsListResponse>> snapshot) {
              if (snapshot.hasData) {
                return RefreshIndicator(
                    onRefresh: () async {
                      bloc.fetchAllFms();
                    },
                    color: globals.fcsBlue,
                    child: ScrollConfiguration(
                      behavior: NoOverScrollBehavior(),
                      child: ListView.builder(
                          shrinkWrap: true,
                          itemCount:
                              snapshot.data != null ? snapshot.data.length : 0,
                          itemBuilder: (BuildContext context, int index) {
                            final fms = snapshot.data[index];
                            //Fill a global list that contains the FMS for this instances
                            globals.currentFMSs.add(
                                FMSBasicInfo(id: fms.id, code: fms.fmsCode));
                            return MyCard(
                              title: _titleContainer(fms.fmsData),
                              fmsId: fms.id,
                              wmId: fms.fmsData.workMachinesList.first
                                  .id, //pass the firs element only for compose the image url
                              imageType: globals.ImageTypeEnum.iteCellLayout,
                              scaleFactor: 4,
                              onPressed: () => _onPressed(fms),
                            );
                          }),
                    ));
              } else if (snapshot.hasError) {
                return Text('Fms snapshot error!');
              }
              return FCSLoader();
            })

引发异常时,我想获取一个快照错误,然后仅查看页面中的文本。

2 个答案:

答案 0 :(得分:0)

您应该将api调用包装在try catch中,然后将错误添加到接收器中。

class FmsBloc {
  final _fmsRepository = Repository();

  final _fmsFetcher = PublishSubject<List<FmsListResponse>>();

  Observable<List<FmsListResponse>> get allFms => _fmsFetcher.stream;

  fetchAllFms() async {
    try {
      List<FmsListResponse> itemModel = await _fmsRepository.fetchAllFms();
      _fmsFetcher.sink.add(itemModel);
    } catch (e) {
      _fmsFetcher.sink.addError(e);
    }
  }

  dispose() {
    _fmsFetcher.close();
  }
}

答案 1 :(得分:0)

标记为正确的答案对我不起作用。进行一些调试时,我发现问题出在捕捉/抛出中:即使您在调试控制台中看到了Exception,您实际上也从未去过那里。

对我来说,在“调试”中应用程序不会崩溃,但是在Exception上会有一个断点,您可以使用“播放”按钮继续播放它。改为使用“运行”按钮,您将具有不带断点的相同行为(例如真实用户)。

这是我的BLoC实现的流程: http调用->提供程序->存储库-> bloc-> ui

我试图处理缺少互联网连接的情况,而不进行检查并处理一般错误情况。

我的证据是提供程序中的 throw Exception('Error'); 不会传播到流程的右侧。我还尝试了其他方法,例如try / catch,并在代码中的不同级别上应用了它们。

基本上,我需要实现的是调用fetcher.sink.addError('Error');。但是从提供程序内部发生错误。然后在用户界面中检查snapshot.hasError将返回true,并且可以轻松处理该错误。

这是唯一对我起作用的(丑陋的)事情:在接收器中将接收器对象作为输入提供给提供程序本身,并在http调用的onCatchError()函数中通过以下方式将错误添加到接收器:它的功能。

我希望它对某人有用。我知道这实际上不是最佳实践,但是我只需要一个快速且肮脏的解决方案。如果有人有更好的解决方案/解释,我会很高兴地阅读评论。