Dart also allows you to store different types of collections of data. Just like primitive data types, you can either create your variables with implicit data types, or allow Dart to infer them.
We’ll look at the three main types:
Lists
List are similar to arrays in Python, Java, C++, and C#. They are an object, so there are methods you can use to work with the lists.
A list is enclosed within square brackets []
, and all of the data elements must be of the same type. A list is guaranteed to keep the elements in the same order as they were entered.
List<int> myIntList = [1,3,5,1,3,5]; // or
var myIntList = [1,3,5,1,3,5]; // both will work
print(myIntList[2]) // print the third element, the element at index 2
print(myInList);
The list is a zero-based index system. The elements don’t have to be unique, and you can add additional elements to the list easily.
Sets
A set is like a mathematical set. A collection of similar types of data, like a list, however, you cannot have duplicate values within the set.
To write a set, you’ll include the elements within curly brackets. We will separate elements with commas. Consider the following example.
Set<int> myset1 = { 1, 2, 3 };
Set<int> myset2 = { 1, 2, 3, 1, 2, 3 };
print(myset1);
print(myset2);
When you print these two statements out, you will see the same output, because the duplicate values are ignored.
Of course, sets, just like list, are objects, so there are methods you can use to work with them.
Maps
Maps are available in many languages. However, they sometimes go by different names, such as dictionaries, associated lists, as well as also being called maps.
A map is a collection of named elements. The name, referenced as an index, has to be unique, however, the values stored can be duplicated.
You will reference the value of the element by using the index.
var data = {'name': 'John Smith', 'occupation': 'Developer'};
print(data);
print(data.runtimeType);
var words = <int, String>{1: 'sun', 2: 'moon', 3: 'stars'};
print(words);
print(words.runtimeType);
Note, you can mix data types in the value of the maps. If you use the runtimeType
, it will show that it is of type object if you mix and match data types.
Dart Datatypes Lists, Sets, and Maps was originally found on Access 2 Learn