심화 문법 공부 후 개인 과제 중 Product class 선언 파트를 구현했다.
선언한 클래스에 map과 for문을 사용하여 리스트에 클래스를 추가했다.
전체 Code
class Product {
String name;
int price;
Product(this.name, this.price);
}
void main() {
Map<String, int> products = {'shirts': 1000, 'skirt': 5000, 'pants': 20000};
List<Product> productList = []; // Product 객체를 저장할 리스트 생성
// for문을 사용하여 Product속성에 Map 데이터를 입력하고 리스트에 추가
for (var key in products.keys) {
productList.add(Product(key, products[key]!));
}
// 결과 출력
for (var product in productList) {
print('${product.name}/ ${product.price}won');
}
}
결과
shirts/ 1000won
skirt/ 5000won
pants/ 20000won
클래스 선언 파트
class Product {
String name;
int price;
Product(this.name, this.price);
}
Product 라는 클래스를 선언해 주고 name, price라는 속성을 부여한다.
Product(this.name, this.price);
원래 이 부분은
Product(String name, int price) {
this.name = name;
this.price = price;
}
이렇게 작성하지만, 위와 같이 짧게 줄여쓸 수 있다.
해당 코드를 이용해 초기값을 설정하지 않은 속성이 null로 처리되는 것을 막고 후에 부여할 값을 사용할 수 있다.
클래스의 생성자 매개변수에 할당값 전달 파트
void main() {
Map<String, int> products = {'shirts': 1000, 'skirt': 5000, 'pants': 20000};
List<Product> productList = []; // Product 객체를 저장할 리스트 생성
// for문을 사용하여 Product속성에 Map 데이터를 입력하고 리스트에 추가
for (var key in products.keys) {
productList.add(Product(key, products[key]!));
}
// 결과 출력
for (var product in productList) {
print('${product.name}/ ${product.price}won');
}
}
데이터가 map 형식으로 제공되었으므로, Product 객체를 저장할 리스트를 생성한다.
for-in문을 사용하여 각각의 key와 value를 각 클래스의 name, price에 부여한다.
리스트를 사용하기 때문에
for (초기화식, 조건식, 증감식) {...}
문보다 for-in의 사용이 더 간단하다.
for, for-in 등 루프문의 사용법과 차이점은
https://dart.dev/language/loops
Loops
Learn how to use loops to control the flow of your Dart code.
dart.dev
위 문서를 참고했다.
추가 참고 문서
https://dart.dev/language/constructors
Constructors
Everything about using constructors in Dart.
dart.dev
'Dart' 카테고리의 다른 글
[Dart] 비동기 프로그래밍 - Future (0) | 2025.03.14 |
---|---|
[Dart] 콘솔 쇼핑몰 트러블슈팅 (0) | 2025.03.13 |
[Dart] 메서드의 사용 (0) | 2025.03.12 |
[Dart] List, Set 개념 및 차이점 (0) | 2025.03.11 |
1주 1일차 - Dart 문법 (0) | 2025.03.07 |