반응형
질문 제목:
Flutter에서 API를 사용하여 중첩된 json 데이터를 호출하는 방법은 무엇입니까?
질문 내용:
내 JSON은 다음과 같습니다.
{
Info: [
{
c_type_id: "1",
cleaning type: "A Cleaning"
},
{
c_type_id: "2",
cleaning type: "B Cleaning"
},
{
c_type_id: "3",
cleaning type: "C Cleaning"
},
{
c_type_id: "4",
cleaning type: "D Cleaning"
},
{
c_type_id: "5",
cleaning type: "E Cleaning"
},
]
}
코드는 다음과 같습니다. 다음 코드는 이 클래스 1에 의해 생성됩니다.
class Album {
List<Info> info;
Album({this.info})
Album.fromJson(Map<String, dynamic> json) {
if (json['Info'] != null) {
info = List<Info>.empty();
json['Info'].forEach((v) {
info.add(new Info.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.info != null) {
data['Info'] = this.info.map((v) => v.toJson()).toList();
}
return data;
}
}
클래스 2:
class Info {
String cTypeId;
String cleaningType;
Info({this.cTypeId, this.cleaningType});
Info.fromJson(Map<String, dynamic> json) {
cTypeId = json['c_type_id'];
cleaningType = json['cleaning type'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['c_type_id'] = this.cTypeId;
data['cleaning type'] = this.cleaningType;
return data;
}
}
다음은 코드를 실행할 때 발생하는 오류입니다. 오류: 인수 유형 'List'는 매개변수 유형 'String'에 할당할 수 없습니다.
도움을 바랍니다!
해결 답변:
문제가 해결된 코드 아래에서 시도해야 합니다. ->
API 호출 기능 선언
Future<List<dynamic>> getInfoData() async {
String url = 'https://fillmmaka.com/gigocleanapi/cleanintypes.php';
var response = await http.get(Uri.parse(url), headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
});
return json.decode(response.body)['Info'];
}
위젯 선언
Center(
child: FutureBuilder<List<dynamic>>(
future: getInfoData(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (context, index) {
var id = snapshot.data[index]['c_type_id'];
var type = snapshot.data[index]['cleaning type'];
return Card(
shape: RoundedRectangleBorder(
side: BorderSide(
color: Colors.green.shade300,
),
borderRadius: BorderRadius.circular(15.0),
),
child: ListTile(
leading: Text(id),
title: Text(type),
),
);
},
),
);
}
return CircularProgressIndicator();
},
),
),
반응형
'expert' 카테고리의 다른 글
Flutter의 화면 간 데이터 전달 (0) | 2023.01.28 |
---|---|
Firestore - 예기치 않은 읽기 (0) | 2023.01.28 |
Dart에서 멤버 변수가 초기화되는 방식에 차이가 있습니까? (0) | 2023.01.24 |
Apple Silicon(M1)에서 CocoaPods를 실행하는 방법 (0) | 2023.01.24 |
재사용 가능한 위젯을 생성하기 위한 함수와 클래스의 차이점은 무엇입니까? (0) | 2023.01.24 |
댓글