[flutter] 과제일지: day12 Class

KoEunseo·2023년 10월 10일
0

flutter

목록 보기
21/45

요구사항

다음의 URL에 네트워크 요청을 보내고, 얻은 데이터를 Class를 통해 생성할 수 있도록 만드시오.

  • 이 때 제작하는 Class 명은 자유입니다.
  • 받아온 네트워크 데이터를 Class에 적용시키고 플러터를 사용하여 다음의 화면을 제작합니다.

class Lecture

class Lecture {
  String name;
  String description;
  String image;
  int price;

  Lecture({
    required this.name,
    required this.description,
    required this.price,
    required this.image,
  });

  Lecture.fromMap(Map<String, dynamic> map)
      : name = map["name"],
        description = map["description"],
        price = map["price"],
        image = map["image"];
}

main.dart

var data = Lecture.fromMap(snapshot.data.data['item'])
이렇게 데이터를 받으면 바로 Lecture 클래스의 fromMap 메서드에 전달해서 Json 데이터를 map으로 변환한다.

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  var dio = Dio();

  Future getData() async {
    var res = await dio.get(url);
    return res;
  }

  
  Widget build(BuildContext context) {
    getData();
    return MaterialApp(
      home: Scaffold(
        body: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            FutureBuilder(
              future: getData(),
              builder: (context, snapshot) {
                if (snapshot.connectionState == ConnectionState.done) {
                  var data = Lecture.fromMap(snapshot.data.data['item']); // 이부분이 핵심
                  return Padding(
                    padding: const EdgeInsets.all(24.0),
                    child: LectureCard(
                      lecture: data,
                    ),
                  );
                }
                return const LinearProgressIndicator();
              },
            ),
          ],
        ),
      ),
    );
  }
}

완성

중간에 서버가 다운돼서 당황했다;
다행히 금방 복구됨. 휴

profile
주니어 플러터 개발자의 고군분투기

0개의 댓글