Darting to Success — Part 2

Markandey Pathak
5 min readApr 10, 2023

--

Darting to Success — Highlight image
Darting to Success

Collection Data Types in Dart

Data types are the building blocks of any application. They allow us to represent and manipulate data in various ways. In addition to the basic data types like numbers and strings, Dart also provides complex data structures such as arrays, lists, maps, and sets, which are essential for handling more complex data. In this article, we will dive into the world of complex data types in Dart, exploring their features, use cases, and how to work with them effectively.

Lists

In Dart, the List type is used to represent arrays, which are dynamic arrays that can grow or shrink in size. Dart does not have a built-in fixed-size array type like some other programming languages.

Declaring and initialising a List

var numbers = [1, 2, 3, 4, 5]; //inferred type List<int>

//or

List<String> names = ['Dart', 'Java', 'JavaScript'];
print(names.length); // 3

Accessing/Modifying elements in a List

print(names[2]); // JavaScript
names[2] = 'C++';
print(names[2]); // C++
print(names.first); // Dart
print(names.last); // C++

Iterating through elements in a List

for(var i=0; i<names.length; i++){
print(names[i]);
}

// or, simply

for(var name in names){
print(name);
}

Adding elements to a List

names[3] = 'PHP'; // throws Index out of range exception

names.add('PHP'); // appends PHP to the list
print(names[3]); // PHP

names.addAll(['Python','R']); // appends Python and R to the list
names.insert(2, 'VBScript'); // inserts VBScript at index 2
// and shifts items to the right
print(names); // [Dart, Java, VBScript, JavaScript, PHP, Python, R]

Removing elements from a List

names.remove('VBScript'); // removes VBScript from the list
print(names); // [Dart, Java, JavaScript, PHP, Python, R]
names.removeAt(2); // removes items at index 2 (JavaScript)
print(names); // [Dart, Java, PHP, Python, R]
names.clear(); // clears the list
print(names); // []

Checking for element existence in a List

names = ['Dart', 'Java', 'JavaScript'];
print(names.contains('Java')); // true
print(names.contains('C#')); // false

In addition to the methods mentioned above, Dart List also provides several other useful methods such as indexOf, lastIndexOf, sublist, replaceRange, retainWhere, and many more for performing various operations on the list.

Dart documentation provides comprehensive information about all the available methods and their usage.

Maps

Maps in Dart are collection objects that store data as key-value pairs. They are also sometimes referred to as dictionaries or associative arrays in other programming languages. In Dart, maps are represented by the Map class, which is part of the core libraries and provides a flexible way to store and manipulate data.

Declaring and initialising a Map

// creating a Map with keys and values of String type
Map<String, String> elements = Map<String, String>();
elements["C"] = "Carbon";
elements["N"] = "Nitrogen";
elements["O"] = "Oxygen";

// or using shorthand

// inferred type is Map<int, String>
var userTypes = {
1: "Admin",
2: "Staff",
3: "User"
};

Accessing/Modifying elements in a Map

print(elements["C"]); // Carbon
print(userTypes[1]); // Admin

userTypes[3] = "Superadmin";
print(userTypes[3]); // Superadmin

Iterating through elements in a Map

To iterate through the key-value pairs of a map in Dart, you can use Map.entries, which is an iterable that contains MapEntry objects representing the keys and values. Each MapEntry object contains a key and a value, allowing you to access and manipulate them during iteration.

You can also use Map.keys and Map.values to iterate through the keys and values of a map in Dart. Map.keys returns an iterable of keys, and Map.values returns an iterable of values. You can use a for loop or other iterable methods to loop through these iterables and access the keys or values of the map.

/* output
C : Carbon
N : Nitrogen
O : Oxygen
*/
for(var element in elements.entries){
print("${element.key} : ${element.value}");
}

/* output
C
N
O
*/
for(var key in elements.keys){
print(key);
}

/* output
Carbon
Nitrogen
Oxygen
*/
for(var value in elements.values){
print(value);
}

Other operations in a Map

Maps in Dart provide several other operations like isEmpty, length, clear, containsKey, putIfAbsent, addAll, remove, update, and forEach. These operations provide flexibility and versatility for managing and manipulating key-value pairs in Dart.

// check if map is empty
print(elements.isEmpty); // false
// check map size
print(elements.length); // 3
// remove all entries
elements.clear();
// check if a key exists
elements.containsKey("C"); // true
// check if a key exists, add if doesn't
elements.putIfAbsent("H", () => "Hydrogen"); // adds key "H" with value Hydrogen
elements.putIfAbsent("C", () => "Carbon"); // does nothing as key "C" exists
// add all elements from a map to another map
// {C: Carbon, N: Nitrogen, O: Oxygen, H: Hydrogen, He: Helieum, Li: Lithium}
elements.addAll({"He": "Helieum", "Li": "Lithium"});

Dart documentation provides comprehensive information about all the available methods and their usage.

Sets

Sets in Dart are unordered collections of unique values, where each value can only appear once in the set. Sets are implemented using the Set class in Dart and provide various methods for performing operations on sets.

Declaring and initialising a Set

You can create a set in Dart using the Set constructor or by using the set literal syntax {}. For example:

Set<int> numbers = Set<int>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.add(2); // ignored as duplicate
print(numbers); // {1, 2, 3}

// OR
var fruits = <String>{"Apple", "Banana", "Orange"};
print(fruits); // {Apple, Banana, Orange}

Accessing/Modifying elements in a Set

print(fruits.elementAt(0)); // Apple
print(fruits.first) // Apple
print(fruits.last) // Orange

fruits.remove("Banana"); // remove Banana from Set
print(fruits); // {Apple, Orange}

Iterating through elements in a Set

You can iterate through the elements of a set using a for-in loop. You can also use skip to skip elements while iterating and take to take a certain number of elements.

/* output
Apple
Orange
*/
for(var fruit in fruits){
print(fruit);
}

var numbers = <int>{1,2,3,4,5,6,7,8,9,10};
// skip first 3 and take next 5
print(numbers.skip(3).take(5)); // (4, 5, 6, 7, 8)

Set Algebra in a Set

Dart provides built-in methods for performing various set operations such as union, difference, intersection, and symmetric difference. The union() method can be used to combine two sets into a new set that contains all elements from both sets, without duplicates. The difference() method returns a new set that contains elements from the first set that are not present in the second set. The intersection() method returns a new set that contains only the elements that are common to both sets. These set operations are powerful tools for manipulating sets in Dart, enabling developers to efficiently perform set-related tasks in their applications.

var users = {"Rob", "Jack", "Julia", "Fatima"};
var admins = {"Julia", "Donald", "Matt"};

print(users.union(admins)); // {Rob, Jack, Julia, Fatima, Donald, Matt}
print(users.intersection(admins)); // {Julia}
print(users.difference(admins)); // {Rob, Jack, Fatima}

Other operations in a Map

Sets in Dart provide several other operations like isEmpty, length, clear, contains, addAll, remove, and forEach. Dart documentation provides comprehensive information about all the available methods and their usage.

Conclusion

In this article, we covered the essentials of working with collections in Dart, including Lists, Maps, and Sets, and explored various collection operations with examples. These powerful data structures are fundamental to Dart programming and can greatly enhance your application development.

In the next article in this series, we will dive into Dart functions in depth, covering topics such as defining functions, passing arguments, returning values, and exploring advanced features like closures and anonymous functions. So stay tuned for the next article in our “Darting to Success” series, where we will continue our journey to becoming a Dart programming expert!

--

--

Markandey Pathak
Markandey Pathak

Written by Markandey Pathak

Expert Engineer & Vice President @ JPMC | Programmer| Javascript Expert | Flutter Enthusiast | Avid Speaker

No responses yet