我正在从正在运行的api中获取数据,但问题是当我打印值时,如果有问题实例,其显示错误
Main.dart
var questions = new List<Questions>();
_getQuestions() {
API.getUsers().then((response) {
setState(() {
Iterable list = json.decode(response.body);
print(list);
print(list);
questions = list.map((model) => Questions.fromJson(model)).toList();
print(questions);
});
});
}
initState() {
super.initState();
_getQuestions();
}
型号
import 'package:flutter/material.dart';
class Questions {
String would;
String rather;
int wouldClick;
int ratherClick;
Questions(int wouldclick, int ratherclick, String would, String rather) {
this.wouldClick = wouldClick;
this.ratherClick = ratherClick;
this.would = would;
this.rather = rather;
}
Questions.fromJson(Map json)
: wouldClick = json['wouldClick'],
ratherClick = json['ratherClick'],
would = json['would'],
rather = json['rather'];
Map toJson() {
return {'wouldClick': wouldClick, 'ratherClick': ratherClick, 'would': would, 'rather': rather};
}
}
在控制台中这样显示
I/flutter ( 4808): [{rather: Tea, would: Coffe, wouldClick: 15, ratherClick: 12}, {rather: Oil, would: Soap, wouldClick: 50, ratherClick: 12}, {rather: Soap, would: Shaving Cream, wouldClick: 15, ratherClick: 12}]
I/flutter ( 4808): [Instance of 'Questions', Instance of 'Questions', Instance of 'Questions']
我需要在JSON中打印问题列表,但它显示了此问题的实例
答案 0 :(得分:2)
您应该在toString
类中覆盖Question
方法
例如
class Questions {
String would;
String rather;
int wouldClick;
int ratherClick;
Questions(int wouldclick, int ratherclick, String would, String rather) {
this.wouldClick = wouldClick;
this.ratherClick = ratherClick;
this.would = would;
this.rather = rather;
}
Questions.fromJson(Map json)
: wouldClick = json['wouldClick'],
ratherClick = json['ratherClick'],
would = json['would'],
rather = json['rather'];
Map toJson() {
return {'wouldClick': wouldClick, 'ratherClick': ratherClick, 'would': would, 'rather': rather};
}
@override
String toString() {
return "Question(would: $would, rather: $rather, wouldClick: $wouldClick, ratherClick: $ratherClick)";
}
}