Dart MapDart Map is an object that stores data in the form of a key-value pair. Each value is associated with its key, and it is used to access its corresponding value. Both keys and values can be any type. In Dart Map, each key must be unique, but the same value can occur multiple times. The Map representation is quite similar to Python Dictionary. The Map can be declared by using curly braces {} ,and each key-value pair is separated by the commas(,). The value of the key can be accessed by using a square bracket([]). Declaring a Dart MapDart Map can be defined in two methods.
The syntax of declaring Dart Map is given below. Using Map LiteralsTo declare a Map using map literal, the key-value pairs are enclosed within the curly braces "{}" and separated by the commas. The syntax is given below. Syntax - Example - 1: Output: {name: Tom, age: 23} Example - 2: Adding value at runtime Output: {name: tom, age: 23, course: B.tech} Explanation - In the above example, we declared a Map of a student name. We added the value at runtime by using a square bracket and passed the new key as a course associated with its value. Using Map ConstructorTo declare the Dart Map using map constructor can be done in two ways. First, declare a map using map() constructor. Second, initialize the map. The syntax is given below. Syntax - After that, initialize the values. Example - 1: Map constructor Output: {name: Tom, age: 23, course: B.tech, Branch: Computer Science} Note - A map value can be any object including NULL.Map PropertiesThe dart:core:package has Map class which defines following properties.
Example - Output: {name: Tom, age: 23, course: B.tech, Branch: Computer Science} The keys are : (name, age, course, Branch) The values are : (Tom, 23, B.tech, Computer Science) The length is : 4 false true Map MethodsThe commonly used methods are given below. addAll() - It adds multiple key-value pairs of other. The syntax is given below. Syntax - Parameter:
Let's understand the following example. Example - Output: Map :{name: Tom, age: 23} Map after adding key-values :{name: Tom, age: 23, dept: Civil, email: [email protected]} remove() - It eliminates all pairs from the map. The syntax is given below. Syntax - Let's have a look at following example. Example - Output: Map :{name: Tom, age: 23} Map after removing all key-values :{} remove() - It removes the key and its associated value if it exists in the given map. The syntax is given below. Syntax - Parameter -
Let's understand the following example. Example - Output: Map :{name: Tom, age: 23} Map after removing given key :{name: Tom} forEach() - It is used to iterate the Map's entries. The syntax is given below. Syntax - Output: Map :{name: Tom, age: 23} name: Tom age: 23 Next TopicDart Symbol |