【发布时间】:2019-10-13 04:28:23
【问题描述】:
在 Flutter 项目中,我遵循 bloc architecture 模式来发出 POST 请求。
我有 2 个模型类,一个用于设置我的 POST 请求的主体 - ModelPostRating,另一个用于接收响应 - ModelPostRatingResponse 来自 POST 请求。
然后,我创建了一个类 ProductRatingPostRequestProvider 用于通过设置请求的正文和标头部分进行 API 调用。
ProductRatingPostRequestProvider.dart
class ProductRatingPostRequestProvider {
Client client = Client();
Future<ModelPostRatingResponse> postLoginResponse(
ModelPostRating modelPostRating) async {
Response response;
print("Product rating request send");
print("productId: ${modelPostRating.productId}");
print("value: ${modelPostRating.value}");
response = await client.post('${my_base_url}/rating',
headers: {
'Content-Type': 'application/json',
},
body: json.encode({
"productId": "${modelPostRating.productId}",
"value": "${modelPostRating.value}"
}));
print('response: ${response.body}');
if (response.statusCode == 200) {
return ModelPostRatingResponse.fromJson(json.decode(response.body));
} else {
throw Exception("Failed to load post");
}
}
}
然后按照 bloc 模式创建另一个类 ProductPostRatingBloc-
ProductPostRatingBloc.dart
class ProductPostRatingBloc {
final _repository = RepositoryProductPostRating();
final _postRatingFetcher = PublishSubject<ModelPostRatingResponse>();
Observable<ModelPostRatingResponse> get postRatingResponse =>
_postRatingFetcher.stream;
fetchRatingPostResponse(
ModelPostRating modelPostRating, BuildContext context) async {
ModelPostRatingResponse modelPostRatingResponse =
await _repository.postRatingRequest(modelPostRating);
print("post rating status: ${modelPostRatingResponse.message}");
showMaterialDialog(modelPostRatingResponse.message, context);
_postRatingFetcher.sink.add(modelPostRatingResponse);
}
}
final blocProductPostRating = ProductPostRatingBloc();
现在,在我展示所有小部件的类中,我有以下代码来发出 POST 请求,同时更改如下所示的评级值-
Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
StarRating(
size: 25.0,
rating: rating2.toDouble(),
color: Colors.orange,
borderColor: Colors.grey,
starCount: starCount,
onRatingChanged: (rating) => setState(
() {
this.rating2 = rating.toInt();
ModelPostRating modelPostRating =
new ModelPostRating(
productId: "1", value: "$rating2");
blocProductPostRating.fetchRatingPostResponse(
modelPostRating, context);
},
),
),
],
),
)
现在,问题是--------
当我按下更改评分时,POST 请求需要时间来给出响应,我想显示 Loading 并在收到响应后将其关闭。
【问题讨论】: