gpt4 book ai didi

flutter - 如何使用 StreamBuilder 管理 block 抛出的异常?

转载 作者:行者123 更新时间:2023-12-01 01:35:07 26 4
gpt4 key购买 nike

当我的提供者在 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');
}
}
}

存储库:
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(
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();
})

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

最佳答案

您应该将 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();
}
}

关于flutter - 如何使用 StreamBuilder 管理 block 抛出的异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56686023/

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