我正在嘗試向我的 POST Http 請求發送一個 json 陣列作為正文,但它會引發此錯誤:
Unhandled Exception: Converting object to an encodable object failed: Instance of 'Athlete'
我想將一個只有運動員模型的三個引數的陣列傳遞給發布請求。你能幫我弄清楚我該怎么做嗎?
我的模型
List<Athlete> athleteFromJson(String str) =>
List<Athlete>.from(json.decode(str).map((x) => Athlete.fromJson(x)));
String athleteToJson(List<Athlete> data) =>
json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class Athlete {
Athlete(
{required this.id,
required this.firstName,
required this.lastName,
required this.fatherName,
required this.currentMonthPresences,
this.isSelected = false,
required this.hasDebt,
this.department,
this.teamKey});
late int id;
late String firstName;
late String lastName;
late String fatherName;
late int currentMonthPresences;
bool isSelected = false;
late bool hasDebt;
final Department? department;
final TeamKey? teamKey;
factory Athlete.fromJson(Map<String, dynamic> json) => Athlete(
id: json['id'],
firstName: json['firstName'],
lastName: json['lastName'],
fatherName: json['fatherName'],
currentMonthPresences: json['currentMonthPresences'],
hasDebt: json['hasDebt'],
department: Department.fromJson(json["department"]),
teamKey: TeamKey.fromJson(json["team"]),
);
Map<String, dynamic> toJson() => {
"id": id,
"firstName": firstName,
"lastName": lastName,
"fatherName": fatherName,
"currentMonthPresences": currentMonthPresences,
"hasDebt": hasDebt,
"department": department?.toJson(),
"teamKey": teamKey?.toJson(),
};
Athlete.newSelectedAthlete(this.id, this.department, this.teamKey);
}
我將陣列發送到 POST 請求的螢屏
class SelectedAthletes extends StatefulWidget {
const SelectedAthletes({Key? key}) : super(key: key);
static const routeName = '/selectedAthletes';
@override
State<SelectedAthletes> createState() => _SelectedAthletesState();
}
class _SelectedAthletesState extends State<SelectedAthletes> {
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
final args = ModalRoute.of(context)!.settings.arguments as List<Athlete>;
return Scaffold(
body: Stack(
children: [
SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ListView.builder(
shrinkWrap: true,
cacheExtent: 34,
primary: true,
physics: const ClampingScrollPhysics(),
padding: const EdgeInsets.only(
top: 10,
bottom: 56,
),
itemCount: args.length,
itemBuilder: (BuildContext context, int index) {
return ListTile(
title: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Text(
'ID: ${args[index].id}',
style: const TextStyle(
color: Colors.blue, fontSize: 14),
),
],
),
Row(
children: [
Flexible(
child: Text(
'${args[index].lastName} ${args[index].firstName}',
style: const TextStyle(
color: Colors.black,
fontFamily: 'Cera',
fontWeight: FontWeight.bold,
fontSize: 18),
),
),
],
),
],
));
},
)
],
),
),
Align(
alignment: Alignment.bottomCenter,
child: Container(
width: double.infinity,
height: 60,
child: ElevatedButton(
style: ElevatedButton.styleFrom(
disabledBackgroundColor: Colors.grey),
onPressed: () async {
ApiService.insertPresences(getJsonArray(args));
},
child: const Center(
child: Text(
'SEND',
style: TextStyle(
fontWeight: FontWeight.bold,
color: Colors.white,
fontSize: 18),
),
),
),
),
),
],
));
}
String getJsonArray(List<Athlete> args) {
var selectedAthletes = <Athlete>[];
for (int i = 0; i < args.length; i ) {
Athlete sa = Athlete.newSelectedAthlete(
args[i].id, args[i].department, args[i].teamKey);
selectedAthletes.add(sa);
}
var jsonExport = json.encode(selectedAthletes);
print(jsonExport);
return jsonExport;
}
}
我的 POST 請求
static Future<Athlete?> insertPresences(String getJson) async {
try {
final response = await http.post(
Uri.parse('$uri/insert-presences'),
headers: <String, String>{
'Authorization': 'Basic ...',
'Content-Type': 'application/json; charset=UTF-8',
'Accept': 'application/json'
},
body: json.encode([
{
"getJson": getJson
}
]),
);
print('Response status: ${response.statusCode}');
print('Response body: ${response.body}');
if (response.statusCode == 200) {
print("status 200");
return null;
} catch (e) {
logger.e(e.toString());
}
return null;
}
我在郵遞員中的原始身體
[
{
"athleteId" : "16198",
"departmentId":"3",
"teamId":"278"
}
]
uj5u.com熱心網友回復:
可能是因為你的模型 toJson 方法,它應該是這樣的
class Athlete {
String? athleteId;
String? departmentId;
String? teamId;
Athlete({this.athleteId, this.departmentId, this.teamId});
Athlete.fromJson(Map<String, dynamic> json) {
athleteId = json['athleteId'];
departmentId = json['departmentId'];
teamId = json['teamId'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['athleteId'] = this.athleteId;
data['departmentId'] = this.departmentId;
data['teamId'] = this.teamId;
return data;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/529306.html
標籤:扑镖
上一篇:如何按順序鏈接多個期貨
下一篇:拍照并在顫動中顯示效果