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

E.B*_*dos 4 dart dart-http flutter

当我的提供者在http.get()调用过程中出现问题时,我试图将快照错误状态返回给我的 StreamBuilder 。在我的情况下,当http.get()返回一个不同于 200 (OK) 的状态时,我抛出一个异常。我希望能够将错误状态返回给快照并针对这种情况执行特定代码。现在,当我抛出异常时,应用程序就会崩溃。

供应商:

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');
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

存储库:

class Repository {
  final fmsApiProvider = FmsApiProvider();

  Future<List<FmsListResponse>> fetchAllFms() => fmsApiProvider.fetchFmsList();
}
Run Code Online (Sandbox Code Playgroud)

集团:

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();
  }
}
Run Code Online (Sandbox Code Playgroud)

我的流构建器:

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();
            })
Run Code Online (Sandbox Code Playgroud)

当抛出异常时,我想获得一个快照错误,然后在我的页面中只可视化一个文本。

Jor*_*ies 8

您应该将 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();
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 是的,这是正确的。然后在您的 StreamBuilder 中使用 snapshot.hasError 为错误情况指定显示的小部件。 (2认同)