다음의 URL에 네트워크 요청을 보내고, 얻은 데이터를 Class를 통해 생성할 수 있도록 만드시오.
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"];
}
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();
},
),
],
),
),
);
}
}
중간에 서버가 다운돼서 당황했다;
다행히 금방 복구됨. 휴