Flutter add vs addAll

줍줍·2023년 9월 2일
0

Flutter

목록 보기
7/11

In Dart and Flutter, add and addAll are methods used for adding elements to a collection like a List or a Set. Here's how they differ:

add

The add method is used to add a single element to the end of a collection.

For example, for a list:

List<int> numbers = [1, 2, 3];
numbers.add(4);  // Adds 4 to the end of the list.
// Now numbers = [1, 2, 3, 4]

addAll

The addAll method is used to add multiple elements to the end of a collection. This method takes an Iterable (which can be a List, a Set, etc.) and adds all elements from that iterable to the collection.

For example, for a list:

List<int> numbers = [1, 2, 3];
numbers.addAll([4, 5, 6]);  // Adds 4, 5, 6 to the end of the list.
// Now numbers = [1, 2, 3, 4, 5, 6]

Summary

  • add adds a single element.
  • addAll adds multiple elements from an Iterable.

Note:

Your previous example with maps was a bit misleading because addAll on maps is used to add all key-value pairs from one map to another. However, add is not a method on Dart's built-in Map class. Here's how addAll could be used for maps:

Map<String, String> map1 = {'key1': 'value1'};
Map<String, String> map2 = {'key2': 'value2', 'key3': 'value3'};

map1.addAll(map2);
// Now map1 = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
profile
쉽게 설명하지 못하면 이해 못한 것

0개의 댓글