728x90

Class Model 생성할 때 key 가 되는 id 가 없이 구현될 경우를 살펴보고자 한다.

값을 수정하거나, 삭제할 때 index 로 삭제해야 한다.

Model 에는 index 가 없기 때문에 asMap 으로 변환하여 index 기준으로 수정, 삭제할 수 있다.

 

Custom Model 대신에 간단한 테스트를 위해 String 으로 대체했다.

Riverpod 용 Provider 로 구현 시에는 _list 대신에 state 로 변경하면 된다.

 

asMap()을 사용하면 Map으로 형변환이 가능하다.

Map 에서 .keys를 사용하면 key 값을, .values를 사용하면 value 값을 가져온다.

map.keys 는 Iterable 객체로 반환되기 때문에 .toList()를 사용해서 변형해줘야 List 객체가 된다.

asMap().entries.map 을 사용하면 새로운 리스트가 만들어진다. entry 조건을 비교하여 값을 update할 수 있다.

class Fruits {
  List<String> _list = const [];
 
  List<String> get list => _list;
 
  void insert(String newItem) {
    _list = [..._list, newItem];
  }
 
  void update(int selectedIndex, String newItem) {
    _list = _list
        .asMap()
        .entries
        .map((entry) => selectedIndex == entry.key ? newItem : entry.value)
        .toList();
  }
 
  void delete(List<String> deleteList) {
    _list = _list.where((item) => !deleteList.contains(item)).toList();
  }
 
  void deleteIndex(int index) {
    _list = List.from(_list)..removeAt(index);
  }
}
 
void main() {
  final fruits = Fruits();
 
  fruits.insert('사과');
  fruits.insert('수박');
  fruits.insert('오이');
  fruits.insert('참외');
  fruits.insert('딸기');
  fruits.insert('배');
  fruits.insert('감');
 
  print(fruits.list); // [사과, 수박, 오이, 참외, 딸기, 배, 감]
  final map = fruits.list.asMap();
  print(map); // {0: 사과, 1: 수박, 2: 오이, 3: 참외, 4: 딸기, 5: 배, 6: 감}
 
  final map_keys = map.keys.toList(); // List 객체
  print(map_keys); // [0, 1, 2, 3, 4, 5, 6]
  print(map.keys); // Iterable 객체 - (0, 1, 2, 3, 4, 5, 6)
  print(map.values); // Iterable 객체 - (사과, 수박, 오이, 참외, 딸기, 배, 감)
 
  print(map.keys is Iterable); // true
  print(map.keys.toList() is List); // true
 
  int selectedIndex = 2;
  fruits.update(selectedIndex, '포도');
  print(fruits.list); // [사과, 수박, 포도, 참외, 딸기, 배, 감]
 
  List<String> deleteList = ['참외''배'];
  fruits.delete(deleteList);
  print(fruits.list); // [사과, 수박, 포도, 딸기, 감]
 
  fruits.deleteIndex(2);
  print(fruits.list); // [사과, 수박, 딸기, 감]
 
  fruits.insert('자두');
  fruits.insert('살구');
  fruits.insert('복숭아');
  print(fruits.list); // [사과, 수박, 딸기, 감, 자두, 살구, 복숭아]
}
 

 

 

 

 

 

 

'Flutter 앱 > Dart 언어' 카테고리의 다른 글

Dart cascade notation  (0) 2024.01.16
Dart List.where  (0) 2024.01.16
Dart fold 함수  (2) 2023.12.15
Dart mixin  (0) 2023.12.11
getter & setter  (0) 2023.12.09
블로그 이미지

Link2Me

,