본문 바로가기
expert

Flutter에서 API를 사용하여 중첩된 json 데이터를 호출하는 방법은 무엇입니까?

by RWriter 2023. 1. 28.
반응형

질문 제목:

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();
      },
    ),
  ),

화면은 다음과 같습니다 ->여기에 이미지 설명 입력

반응형

댓글