【问题标题】:how to implement pagination in flutter using dio如何使用dio在flutter中实现分页
【发布时间】:2022-01-05 18:08:20
【问题描述】:

我正在尝试在我的颤振应用中实现分页。我以这种方式使用 MVVM 架构组织了我的数据 -

search_view.dart - 它包含用户可见的listview。首先,它调用方法initilize,该方法初始化总线列表并将其存储在itemBusList变量中。它从 - model.itemBusList (基准类型的列表)中获取列表,并将其与 ListView.builder 一起使用。

search_model.dart - 它包含变量itemBusList 并具有功能 -

fetchBuses() async {
    tripsResponse = await (_databaseService.requestTrips(
      object: object!,
    ));
    setBusy(false);
    if (tripsResponse?.data != null) {
      itemBusList.clear();
      itemBusList.addAll(tripsResponse?.data.data);
      notifyListeners();
    }
    else {
      itemBusList.clear();
      //empty list
    }
  }

它正在使用 - 获取数据

tripsResponse = await (_databaseService.requestTrips(
      object: object!,
    ));

_databaseService 是DatabaseService 类型的变量。

databse_service.dart - 它主要是获取 api 和以有用的方式存储/转换数据之间的连接线。我用这个requestTrips 来获取我的总线数据-

Future<BaseData?> requestTrips({
    required TripRequestDto object,
  }) async {
    Response response = await _apiService.handlePost(
      body: object.toMap(),
      type: FetchDataType.TRIP_REQUEST_DTO_RESPONSE,
    );
    return response.data;
  }

这里,_apiService 是一个ApiService 类型的对象,该类处理api 调用。

api_service.dart - 

Future<Response<BaseData<dynamic>>> handlePost({
    Map<String, dynamic>? body,
    Map<String, dynamic>? parameters,
    Map<String, dynamic>? extras,
    FetchDataType? type,
  }) async {
    Dio dioNetwork;

    try {
      Map<String, dynamic> requiredData = await fetchCredentials(type, extras);

      dioNetwork = initDioObject(requiredData['version'], type);

      return await dioNetwork.post(
        requiredData['path'],
        queryParameters: parameters,
        data: body,
        options: Options(headers: getHeaders(requiredData)),
      );
    } catch (e) {
      print(e);
      print('got an error while api call');
      Response<BaseData<dynamic>> response =
          Response(requestOptions: RequestOptions(path: ''));
      response.data = BaseData(
          success: false,
          data: null,
          message: _setErrorMessage(e as DioError),
          statusCode: serverError(e));
      return response;
    }
  }

现在,我怎样才能一次获得 5 个响应,并一直持续到最后。我希望一次出现 5 个用于分页的元素,当我刷新时,再出现 5 个并继续。我是新手,请帮助我。

这里是基准类-

class Datum {
  Datum({
    this.trip,
    this.nodes,
    this.vehicle,
    this.canPolicy,
    this.cashBookAllowed,
    this.bookAllowed,
    this.reschedulePolicy,
    //this.totalPages,
  });

  Trip? trip;
  List<NodeElement>? nodes;
  Vehicle? vehicle;
  Policy? canPolicy;
  bool? cashBookAllowed;
  bool? bookAllowed;
  Policy? reschedulePolicy;
  //int? totalPages;

  factory Datum.fromJson(Map<String, dynamic> json) => Datum(
        trip: json["trip"] == null ? null : Trip.fromJson(json["trip"]),
        nodes: json["nodes"] == null
            ? null
            : List<NodeElement>.from(
                json["nodes"].map((x) => NodeElement.fromJson(x))),
        vehicle:
            json["vehicle"] == null ? null : Vehicle.fromJson(json["vehicle"]),
        canPolicy: json["canPolicy"] == null
            ? null
            : Policy.fromJson(json["canPolicy"]),
        cashBookAllowed:
            json["cashBookAllowed"] == null ? null : json["cashBookAllowed"],
        bookAllowed: json["bookAllowed"] == null ? null : json["bookAllowed"],
        reschedulePolicy: json["reschedulePolicy"] == null
            ? null
            : Policy.fromJson(json["reschedulePolicy"]),
        //totalPages: json["totalPages"] == null ? null : json["totalPages"],
      );

  Map<String, dynamic> toJson() => {
        "trip": trip == null ? null : trip!.toJson(),
        "nodes": nodes == null
            ? null
            : List<dynamic>.from(nodes!.map((x) => x.toJson())),
        "vehicle": vehicle == null ? null : vehicle!.toJson(),
        "canPolicy": canPolicy == null ? null : canPolicy!.toJson(),
        "cashBookAllowed": cashBookAllowed == null ? null : cashBookAllowed,
        "bookAllowed": bookAllowed == null ? null : bookAllowed,
        "reschedulePolicy":
            reschedulePolicy == null ? null : reschedulePolicy!.toJson(),
        //"page" : totalPages == null ? null : totalPages
      };
}

这是课堂之旅-

class Trip {
  Trip({
    this.tripId,
    this.origin,
    this.dest,
    this.code,
    this.timeSlot,
    this.schStart,
    this.schEnd,
    this.minPrice,
    this.minBasePrice,
    this.freeSeats,
    this.totalKm,
    this.vehicleTypeId,
    this.nonStop,
    this.status,
    this.serviceId,
  });

  int? tripId;
  Dest? origin;
  Dest? dest;
  String? code;
  int? timeSlot;
  int? schStart;
  int? schEnd;
  double? minPrice;
  double? minBasePrice;
  int? freeSeats;
  int? totalKm;
  int? vehicleTypeId;
  bool? nonStop;
  StatusClass? status;
  String? serviceId;

  factory Trip.fromJson(Map<String, dynamic> json) => Trip(
        tripId: json["tripId"] == null ? null : json["tripId"],
        origin: json["origin"] == null ? null : Dest.fromJson(json["origin"]),
        dest: json["dest"] == null ? null : Dest.fromJson(json["dest"]),
        code: json["code"] == null ? null : json["code"],
        timeSlot: json["timeSlot"] == null ? null : json["timeSlot"],
        schStart: json["schStart"] == null ? null : json["schStart"],
        schEnd: json["schEnd"] == null ? null : json["schEnd"],
        minPrice: json["minPrice"] == null ? null : json["minPrice"],
        minBasePrice:
            json["minBasePrice"] == null ? null : json["minBasePrice"],
        freeSeats: json["freeSeats"] == null ? null : json["freeSeats"],
        totalKm: json["totalKM"] == null ? null : json["totalKM"],
        vehicleTypeId:
            json["vehicleTypeId"] == null ? null : json["vehicleTypeId"],
        nonStop: json["nonStop"] == null ? null : json["nonStop"],
        status: json["status"] == null
            ? null
            : StatusClass.fromJson(json["status"]),
        serviceId: json["serviceId"] == null ? null : json["serviceId"],
      );

【问题讨论】:

  • 你的 API 支持分页吗?
  • 是的,确实如此。我应该如何实施?

标签: flutter api dart


【解决方案1】:

在您的情况下,您需要在请求中添加参数以进行查询。类似这样:

_apiService.handlePost(
  body: object.toMap(),
  type: FetchDataType.TRIP_REQUEST_DTO_RESPONSE,
  parameters: {
    'limit': 10,
    'offset': 0,
  }
)

其中limit 和offset 相当于API 中的分页参数。此外,您需要将限制和偏移值存储在局部变量中。

【讨论】:

  • 如果没有这些参数,我可以进行分页吗?我的意思是,我可以手动调用一次获取 10 个列表项,然后在再次发出请求时,下一个 10 个,依此类推
  • 您可以使用infinite_scroll_pagination 插件或编写自己的解决方案。
  • 我试过了,但没能实现。你能帮帮我吗
  • 您是否面临API实现或UI实现的问题?
  • 我被困在如何进行 api 调用上,这样一次只加载 5 个项目,再次调用时,下一个 5 等等..,分别是我的 api 没有t 本身支持分页
猜你喜欢
  • 2021-01-24
  • 2021-04-27
  • 2021-03-26
  • 2019-09-27
  • 2019-05-24
  • 2021-09-29
  • 2022-01-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多