我正在尝试从API检索数据列表。
这是API的响应:
{"permission_requests":[{"id":1,"created_at":"2020-11-02","reason":"Aliquid cum autem id reprehenderit quam quis voluptate enim dolorem magnam doloremque et.","status":"cancelled","date":"06 Nov - 10 Nov","note":"Odit a exercitationem iure culpa voluptatem.","is_pending":false,"type_id":7},{"id":5,"created_at":"2020-11-02","reason":"Rerum incidunt explicabo accusantium nemo commodi quos sed et.","status":"refused","date":"13 Oct - 17 Oct","note":"Corporis ad omnis animi.","is_pending":false,"type_id":2},{"id":11,"created_at":"2020-11-02","reason":"Eveniet sed laudantium vitae perspiciatis molestiae sint minus dolores dolor numquam maxime facere deleniti velit.","status":"cancelled","date":"26 Sep","note":"Debitis perferendis officia aliquam dolor recusandae.","is_pending":false,"type_id":7},{"id":14,"created_at":"2020-11-02","reason":"Ut natus corporis necessitatibus et maiores accusamus repudiandae quas commodi consequatur ratione optio velit ducimus aut.","status":"accepted","date":"26 Sep","note":"Unde possimus laudantium doloribus voluptate ullam.","is_pending":false,"type_id":2},{"id":17,"created_at":"2020-11-02","reason":"Ut vel ea minus sint nemo et ex aut repellendus recusandae ex laboriosam sed aliquam veniam voluptas.","status":"pending","date":"26 Sep","note":"Minima ullam itaque quae ex inventore voluptatum.","is_pending":true,"type_id":4},{"id":24,"created_at":"2020-11-02","reason":"Rerum dignissimos est deserunt dolor aliquam qui repellat sequi quasi culpa rerum.","status":"accepted","date":"19 Sep - 2h","note":"Architecto ab inventore id est.","is_pending":false,"type_id":5},{"id":29,"created_at":"2020-11-02","reason":"Quas aspernatur impedit ea porro accusamus quas voluptatem magni temporibus velit error suscipit ab molestias in omnis.","status":"refused","date":"19 Sep - 2h","note":"Sunt beatae sit quia voluptates et enim cumque ut.","is_pending":false,"type_id":5}]}
这是我的代码:
import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:richiesta_permessi/const.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:richiesta_permessi/exceptions/exceptions.dart';
import 'package:richiesta_permessi/models/permission_request.dart';
import 'package:richiesta_permessi/repositories/authentication.dart';
abstract class PermissionRequestsRepository {
Future<List<PermissionRequestModel>> getPermissionRequests();
Future<bool> sendCancelRequest(String permissionRequestId);
}
class RestPermissionRequestsRepository extends PermissionRequestsRepository {
List<PermissionRequestModel> permissionRequests;
var httpClient = new Dio();
@override
Future<List<PermissionRequestModel>> getPermissionRequests() async {
try {
Future<SharedPreferences> _prefs = SharedPreferences.getInstance();
final SharedPreferences prefs = await _prefs;
String token = prefs.getString('user_token') ?? null;
if (null == token) {
throw PermissionRequestsException(
message: 'Non è stato possibile recuperare la lista delle richieste',
);
}
httpClient.options.headers['content-Type'] = 'application/json';
httpClient.options.headers['Authorization'] = 'Bearer $token';
Response response = await httpClient.get(kGetPermissionRequestsUrl);
if (response.statusCode != 200) {
throw PermissionRequestsException(
message: 'Non è stato possibile recuperare la lista delle richieste',
);
}
final permissionList = response.data['permission_requests'];
final List<PermissionRequestModel> permissionRequests = permissionList.map((value) => PermissionRequestModel.fromJson(value)).toList();
print('The list is done');
return permissionRequests;
} catch (e) {
throw PermissionRequestsException(
message: 'Non è stato possibile recuperare la lista delle richieste',
);
}
}
@override
Future<bool> sendCancelRequest(String permissionRequestId) async {
try {
await Future.delayed(Duration(seconds: 1));
return true;
} catch (e) {
throw PermissionRequestsException(
message: 'Non è stato possibile annullare la richiesta',
);
}
}
}
这是PermissionRequestModel:
import 'package:meta/meta.dart';
class PermissionRequestModel {
final String id;
final String reason;
final String status;
final String note;
final String date;
final bool isPending;
PermissionRequestModel({
@required this.id,
@required this.reason,
@required this.status,
@required this.note,
@required this.date,
@required this.isPending,
});
factory PermissionRequestModel.fromJson(Map<String, dynamic> json) {
return PermissionRequestModel(
id: json['id'].toString(),
reason: json['reason'],
status: json['status'],
note: json['note'],
date: json['date'],
isPending: json['is_pending'],
);
}
}
该应用程序具有一个BloC,该BloC可以调用存储库,并且请求已正确发出,它可以调用API并检索数据。
数据存储在变量中,但是fromJson
似乎从未完成,我尝试打印value
且它仅传递一次,无法弄清原因。
无法理解问题所在,print('The list is done');
已经到达。
编辑:
我更改了代码,现在添加了一个简单的for循环:
List<PermissionRequestModel> permissionRequests;
for (int i = 0; i < permissionList.length; i++) {
permissionRequests.add(PermissionRequestModel.fromJson(permissionList[i]));
}
即使使用此代码,它也不会返回任何内容,如果我使用此代码手动添加数据,它将起作用:
permissionRequests = [
PermissionRequestModel(
id: '1',
reason: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.',
status: 'cancelled',
note: 'Nulla facilisi. Donec mi risus, fringilla a felis ut, auctor placerat leo. Vivamus non placerat eros. Donec quis ullamcorper velit. Vestibulum nec ante efficitur, elementum urna et, feugiat est. Maecenas vel cursus nulla.',
date: '20 ottobre',
),
PermissionRequestModel(
id: '2',
reason: 'In in eros non sapien tempor egestas at nec tellus',
status: 'refused',
note: 'Nulla facilisi. Donec mi risus, fringilla a felis ut, auctor placerat leo. Vivamus non placerat eros. Donec quis ullamcorper velit. Vestibulum nec ante efficitur, elementum urna et, feugiat est. Maecenas vel cursus nulla.',
date: 'Dal 20 al 22 ottobre',
),
PermissionRequestModel(
id: '3',
reason: 'Nam ut condimentum dui. Nulla sed ultrices lacus. egestas at nec tellus',
status: 'pending',
note: 'Nulla facilisi. Donec mi risus, fringilla a felis ut, auctor placerat leo. Vivamus non placerat eros. Donec quis ullamcorper velit. Vestibulum nec ante efficitur, elementum urna et, feugiat est. Maecenas vel cursus nulla.',
date: '20 ottobre - 3 ore',
),
];
这怎么可能?有什么区别?
编辑2:
好的,问题是当我尝试使用permissionRequests
时的.add
,由于某种原因,它只是试图解析第一个元素,然后它永远运行
答案 0 :(得分:0)
好吧,如果有人遇到相同的错误,问题就出在列表的初始化上。
不知道为什么,但这不起作用:
List<PermissionRequestModel> permissionRequests;
permissionRequests.add(Object)
在此有效:
List<PermissionRequestModel> permissionRequests = [];
permissionRequests.add(Object)