Flutter Dart Convert Map to List & List to Map
Last updated Apr 03, 2022In this post we are going to cover about What is List and Map and How to convert list to map and map to list with dart programming.
In any programming language array is the common data type to manage the collection of data. In dart we will use List to manage group of data. List is an group of ordered list data. To use List we will use dart:core package
In dart List could be divided in two parts
- Fixed Length List
- Growable List
Fixed Length List : A fixed length list can't change its length at runtime. We will create Fixed Length list like below
var list = new List(SIZE_OF_LIST); |
Simple Fixed Length List example
void main() { |
This will print below output
[1, 2, 3,12] |
Growable List : Its a Growable list where length can change at runtime.
var list = new List(growable:true); |
What is Map in dart?
When we want to store the data with aperticular names then we will use Maps. Map is an collection data typw which will store the data in the form of Key/Value pair. Map can change at runtime, it can grow or shrink on the run time.
we can declare map in two ways
- Using Map Literals
- Using a Map constructor
Delcare Map using Map Listerals
var mapName = { key1:value1, key2:value2 ,.... } |
Simple Map example using Map Literals
void main() { |
Till now we discussed what is Map and List in dart, let learn how to convert Map to List in dart
class Student { Student(this.name, this.marks); @override |
Let create a Simple Map object which will contains info about the Students
var student=Student(name:"Student1",marks:230); |
Now let create an Empty list object
var studentList = []; |
Convert Map to list using Map forEach() method
studentMap.forEach((k, v) => studentList.add(v); |
Here we generated list from map using key,values and will print below out put
void main() { |
class Student { Student({this.name, this.marks}); @override |
Convert List to Map in Dart/Flutter
Now Let's create a List with Student Info
List list = []; |
Convert List to Map Using Iterable forEach() method
We can convert Dart List to Map in another way: forEach() method
var map = {}; |
Output:
{Student1: 231, Student2: 432, Student3: 123} |
void main() { |
class Student { Student({this.name, this.marks}); @override |
Read dart list tutorial
Compare list and maps using DeepCollectionEquality collection class
Conclusion: In this Dart tutorial we covered how to convert list to map and map to list in different ways
Read More
Article Contributed By :
|
|
|
|
23069 Views |