【发布时间】:2021-06-12 07:27:35
【问题描述】:
我正在开发一个使用 Flutter Web 和 RESTful API 作为后端的 Web 应用程序。 所以,我正在尝试从 api 中获取数据,使用 Flutter Models 对其进行序列化,然后返回结果。
问题是,我得到了这个结果
Expected a value of type 'Map<String, dynamic>', but got one of type 'List<dynamic>'
如何解决这个问题?
这是我的颤振代码:
模型
// To parse this JSON data, do
//
// final medicalRecordsModel = medicalRecordsModelFromJson(jsonString);
import 'dart:convert';
class MedicalRecordsModel {
MedicalRecordsModel({
this.id,
this.category,
this.fileName,
this.dateTimestamp,
this.description,
this.upload,
this.patientName,
this.age,
this.address,
this.userId,
this.patientId,
this.isActive,
});
final String id;
final String category;
final String fileName;
final String dateTimestamp;
final String description;
final String upload;
final String patientName;
final String age;
final String address;
final dynamic userId;
final int patientId;
final bool isActive;
factory MedicalRecordsModel.fromJson(Map<String, dynamic> json) {
return MedicalRecordsModel(
id: json["id"],
category: json["category"],
fileName: json["fileName"],
dateTimestamp: json["dateTimestamp"],
description: json["description"],
upload: json["upload"],
patientName: json["patientName"],
age: json["age"],
address: json["address"],
userId: json["userId"],
patientId: json["patientId"],
isActive: json["isActive"],
);
}
}
API 连接
import 'dart:convert';
import 'dart:developer';
import 'dart:async';
import 'package:app/src/constants/medical_records.dart';
import 'package:app/src/models/medical_records/medical_records.dart';
import 'package:app/src/pages/Medical-Records/medical_record.dart';
import 'package:http/http.dart' as http;
class MedicalRecordsManager {
var client = http.Client();
var url = ConstantMedicalRecords.medical_records_api;
Future<MedicalRecordsModel> getRecords() async {
var url = ConstantMedicalRecords.medical_records_api;
log('$url');
try {
final response = await client.get(url);
if (response.statusCode == 200) {
return MedicalRecordsModel.fromJson(jsonDecode(response.body));
// print(recordsModel);
}
} catch (Exception) {
print(Exception);
print("Error occured");
}
}
}
这是我要获取的 JSON 数据
{
"id": "103",
"category": "DOCUMENT",
"fileName": "Check Up",
"dateTimestamp": "2021-02-1012:59:46",
"description": "string",
"upload": "String",
"patientName": "1",
"age": "25",
"address": "Earth",
"userId": null,
"patientId": 12,
"isActive": true
}
请帮我解决这个问题。
【问题讨论】:
-
你确定你只返回一个 MedicalRecordsManager 吗?...基于命名 getRecords().. 它应该是 Future
- >?.. 尝试打印出 json 响应并调试好
-
@Reign 我想返回的不仅仅是数据
-
您可以使这个过程变得更容易。请看这个答案。仅使用一个函数调用,您就可以得到最终结果。此方法已经过测试并在测试中涵盖。 stackoverflow.com/a/66632608/1737201
-
这些答案都不起作用吗?
标签: flutter dart flutter-web