-
Map타입으로 선언된 변수의 활용을 도와주는 함수들(containKey, putIfAbsent, update)프로그래밍 공부 메모/flutter 2022. 11. 28. 22:12맵 타입으로 선언된 변수Map<String, CartItem> _items
containKey()
- 해당 맵의 키 값이 있는지 없는지 확인 참, 거짓 값을 리턴
putIfAbsent()
- 키 값을 조회하여 만약 없다면 새로운 키에 value값을 연결 후 리턴
update()
- 기존의 키 값이 존재한다면, 해당 키 값의 value를 업데이트한다
import 'package:flutter/material.dart'; class CartItem { final String id; final String title; final int quantity; final double price; CartItem( {required this.id, required this.title, required this.quantity, required this.price}); } class Cart with ChangeNotifier { late Map<String, CartItem> _items; Map<String, CartItem> get _items { return {..._items}; } void addItem(String productId, double price, String title) { if (_items.containsKey(productId)) { _items.update( productId, (existingCartItem) => CartItem( id: existingCartItem.id, title: existingCartItem.title, quantity: existingCartItem.quantity + 1, price: existingCartItem.price), ); } else { //putIfAbsent-> [key]의 값을 조회하거나 없는 경우 새로운 값이 지정되어 있으면 새로운 값을 리턴 //[key]에 연결된 값이 있는 경우 해당 값을 반환합니다. _items.putIfAbsent( productId, () => CartItem( id: DateTime.now().toString(), title: title, quantity: 1, price: price), ); } } }
반응형'프로그래밍 공부 메모 > flutter' 카테고리의 다른 글
as (형 변환 / 접두사 지정), show 활용하기 (0) 2022.11.30 유용한 위젯(chip / badges) (0) 2022.11.29 mixin / with는 무엇인가? (0) 2022.11.27 함수를 생성자로 전달하기(부제 : double.parse) (0) 2022.09.18 Dart 생성자(constructor)의 종류 (0) 2022.09.09