【问题标题】:How to show Loading by making a POST request on changing star rating following bloc pattern in Flutter?如何通过在 Flutter 中按照 bloc 模式更改星级的 POST 请求来显示加载?
【发布时间】: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 并在收到响应后将其关闭。

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    虽然回答这个问题的时间太长了,但我想分享我使用 bloc 模式做同样事情的方式。 我会在 blocbuilder 状态中渲染评级小部件,并且在评级更改时,我会调用我的 bloc 事件来更改评级,该评级将从服务器传输等待的响应。 在 bloc builder 中,我会渲染加载指示器,直到 bloc 状态更改为评级更改状态。

    bloc类的sn-p

    @override
    Stream<BlocStateClass> mapEventToState(BlocEventClass event) async* {
    if (event is ChangeRatingEvent) {
      try {
       // here you can make your api call to update the rating and get the response
       RatingMaster ratingMaster=
            await repository.changeRating(event.rating);
    
        yield RatingUpdatedState(ratings: ratingMaster);
      } catch (e) {
        yield BlockErrorState(message: e.toString());
      }
    }
    

    }

    我将使用以下代码呈现评分小部件

    BlocBuilder<BlocClass, BlocStateClass>(
         bloc: _xyzBloc, // bloc instance
         builder: (context, state) {
            if (state is InitState) {
               return buildDefaultRating();
            }else if (state is LoadingState) {
               return buildLoading();
            } else if (state is BlockErrorState) {
               return buildErrorUi(state.message);
            } else if (state is RatingUpdatedState) {
               return _updateratingWidget(state.ratings, context);
            }
    })
    

    这一行将有助于将事件添加到 onRatingChanged 函数的 bloc 中

    _xyzBloc.add(ChangeRatingEvent(rating: rating));
    

    我希望这可以帮助有需要的人。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-12-10
      • 2021-02-22
      • 2019-04-28
      • 1970-01-01
      • 2020-11-25
      • 1970-01-01
      • 2019-08-30
      相关资源
      最近更新 更多