Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Mobile

DART2 Prima Plus - Tutorial 2 - LIST

5.00/5 (2 votes)
9 Jul 2018CPOL6 min read 11.4K   67  
In this second article of series, I would be focusing completely on List working

Introduction

This article is the second in the series for learning Dart language, the new kid on the block. Dart Team was upgrading language almost at the same pace of .NET Core. With Flutter making its main language for app development, I believe it would be in mainstream soon.

In this article, I would be talking about List type, which is an amalgamation of normal Array and List of C++, similar to System.Collection.Generic.List data structure of C#.

Background

I am going to discuss the following properties and methods of List class, this class is defined in package Dart:Core package, since DART is opensource, you can check its code in list.dart file. I am going to discuss the following properties provided by List class. Definition and declaration are taken from the DART website. If you need to understand how to create project, please refer to the first article of series here.

  1. Task#1 Creation
    1. List(int length) - Create a list of the given length
    2. List.filled(int length,E fill,{bool growable:false}) - Create a fixed length list of the given length and initialise the value of each position with fill argument
    3. List.generate(int length, E generator(int index),{bool gowable:true}) - generate a list of values based on generator function based on length argument
    4. List.unmodifable(Iterable elements) - Create an unmodifiable list containing all elements.
    5. List.from(Iterable elements,{bool growable:false}) - Create a list containing all the elements.
    6. static List.copyRange<T>(List<T> target, int at, List<T> source, [int start, int end]): copy source list to target, starting from at, you can also specify start (inclusive) and end (exclusive) of source list to copy.
  2. Task#2 Properties
    1. first - Return first element from list
    2. last - Return last element from list
    3. length - Return length of list
    4. reversed - Reverse the list
    5. isEmpty - Check if the list is empty
    6. isNotEmpty - Check if the list is non-empty
    7. runtimeType - Object type, similar to type in C#
  3. Task#3 Add/Delete Data
    1. add(E value), addAll(Iterable<E> iterable) - Add Value/iterable to list
    2. asMap() - Returns an unmodifiable Map of list, key would be index, and list item as value
    3. fillRange(int start, int end, [ E fillValue ])/ Iterable<E> getRange(int start, int end) - Sets the objects in the range start inclusive to end exclusive to the given fillValue / Returns an Iterable that iterates over the objects in the range start inclusive to end exclusive.
    4. insert(int index, E element)/ insertAll(int index, Iterable<E> iterable) - Inserts the object at position index in this list / Inserts all objects of iterable at position index in this list & Inserts all objects of iterable at position index in this list.
    5. setAll(int index, Iterable<E> iterable) /setRange(int start, int end, Iterable<E> iterable, [ int skipCount = 0 ]) - Copies the objects of iterable, skipping skipCount objects first, into the range start, inclusive, to end, exclusive, of the list.
    6. take(int count)/takeWhile(bool test(E value)) - Returns a lazy iterable of the count first elements of this iterable. / Returns a lazy iterable of the leading elements satisfying test.
    7. fold<T>(T initialValue, T combine(T previousValue, E element)) - Reduces a collection to a single value by iteratively combining each element of the collection with an existing value
    8. join([String separator = "" ]) - Converts each element to a String and concatenates the strings
    9. remove(Object value)/removeAt(int index)/removeLast() - Removes the first occurrence of value from this list / Removes the object at position index from this list / Pops and returns the last object in this list.
    10. removeRange(int start, int end) - Removes the objects in the range start inclusive to end exclusive.
  4. Task#4 Find and where is data
    1. indexOf(E element, [ int start = 0 ]) - Returns the first index of element in this list.
    2. elementAt(int index) - Returns the indexth element.
    3. lastIndexOf(E element, [ int start ]) - Returns the last index of element in this list.
    4. any(bool f(E element)) - Checks whether any element of this iterable satisfies test.
    5. sublist(int start, [ int end ]) - Returns a new list containing the objects from start inclusive to end exclusive.
    6. where(bool test(E element)) - Returns a new lazy Iterable with all elements that satisfy the predicate test.
    7. singleWhere(bool test(E element)) - Returns the single element that satisfies test.
    8. firstWhere(bool test(E element), { E orElse() }) - Returns the first element that satisfies the given predicate test.
    9. lastWhere(bool test(E element), { E orElse() }) - Returns the last element that satisfies the given predicate test.
    10. retainWhere(bool test(E element)) - Removes all objects from this list that fail to satisfy test
    11. removeWhere(bool test(E element)) - Removes all objects from this list that satisfy test.

Using the Code

I have divided the tutorial in four tasks, I will discuss each task separately.

Task#1

In this section, I am going to discuss various creation methods provided by DART for creation or initial filling up data in List, I am covering all 6 methods here. You can check creation.dart file in the attached zip for the same.

C++
void creation()
{

// 1.0 Basic List
List<int> listOfInt = new List<int>();


// 1.1 with Length
List<int> listOfIntWithLength = new List<int>(5);


//1.2 Using List.filled when list is fixed length
List<int> listofIntFilledFixed = new List<int>.filled(5, 1);


try{

//this will throw error
listofIntFilledFixed.add(5);

}
catch(ex)
{
  print(ex);
}

// 1.2(a) using List.filled, now list is growable

List<int> listofIntFilledGrowable = new List<int>.filled(5, 1,growable:true);
listofIntFilledGrowable.add(5);


// 1.3 using List.generate, you can specify your own function to provide value to list
// => is way to write shorthand function, the list would contain 1,2,3,4,5
// as list in dart is zero index based

List<int> listofIntGenerate = new List<int>.generate(5,(int index)=> index+1);


//1.5 Using List.from, it will also have 1,2,3,4,5

List<int> listOfIntFrom = new List<int>.from(listofIntGenerate);

// 1.4 Using List.unmodifiable list with created list

List<int> listOfIntunmodifiable = new List<int>.unmodifiable(listofIntGenerate);

try{

//this will throw error
listOfIntunmodifiable.add(5);

}
catch(ex)
{
  print(ex);
}

//1.6 Using List.copyRange, you need to specify length of target before hand

List<int> listOfIntWithcopyRange = new List<int>(3);
List.copyRange(listOfIntWithcopyRange, 0, listOfIntunmodifiable,0,3);
}

I have provided relevant comments in code itself to demonstrate various code snippets. Here, we reached the end of Task#1.

Task#2

In this task, I will demonstrate the use of first, last, length, reverse, isEmpty, isNotEmpty, runtimeType properties supplied by DART:List class. The code is written in property.dart, which is in the attached zip file.

C++
void properties()
{
// Create List with pre filled items : 1,2,3,4,5
List<int> listIntProperties = new List.generate(5,(int index)=>index+1,growable: true);

// Demonstrate use of first, last and length property
print("First : ${listIntProperties.first}, Last : ${listIntProperties.last} 
       and number of elements are ${listIntProperties.length}");

//-- Print list in reverse
listIntProperties.reversed.forEach((int item){ print('item ${item}');});

//-- Demonstrate use of isEmpty, isNotEmpty, and runtimeType
print("isEmpty : ${listIntProperties.isEmpty}, isNotEmpty : ${listIntProperties.isNotEmpty} 
       and ObjectTyp ${listIntProperties.runtimeType}");
}

Image 1

Here we reached end of Task #2.

Task#3

In this code, I am going to discuss add(E value) , addAll(Iterable<E> iterable), asMap(), fillRange(int start, int end, [ E fillValue ])/ Iterable<E> getRange(int start, int end), insert(int index, E element)/ insertAll(int index, Iterable<E> iterable). Look for below code in listadd() in listadd.dart.

C#
void listadd()
{
//-- this list will contain 1,2,3,4,5
List<int> listIntAdd = new List.generate(5,(int index)=>index+1,growable: true);

// this list will contain 10,11
List<int> listIntAdd2 = new List.generate(2,(int index)=>index+10,growable: true);

// Task 3.1 add and addAll
listIntAdd.add(6);

// List.join (Task#3.8), join all element as string, I will talking more about in its separate section.
print("After Task 3.1 add (listIntAdd)= " + listIntAdd.join(","));

listIntAdd.addAll(listIntAdd2);
print("After Task 3.1 addAll (listIntAdd) = " + listIntAdd.join(","));

//Task 3.2, converting it to map, map is key value data structure, 
//if you have C++ background, its similar to stl::map
// otherwise if you from C# background its similar to Dictionary

print("Task#3.2 asMap()");

listIntAdd2.asMap().forEach((key,value){ print("key ${key} value is ${value}");});

//Task 3.3 fillRange and getRange, here i have created list with 3 element, I would fill all with 5

List<int> listIntfillRange = new List.generate(3,(int index)=>5,growable: true);

listIntfillRange.fillRange(0, 3, 5);

print("After Task 3.3 fillRange (listIntfillRange) = " + listIntfillRange.join(","));

// Now for checking getRange, we will get data from listIntAdd, we will get range starting
// from 3rd element to 5th, so overall 2 element would be displayed

print("After Task 3.3 getRange (listIntAdd) = " + listIntAdd.getRange(3,5).join(","));

//Task 3.4 insert and insert all
// I would insert element 7 at 2nd location

listIntfillRange.insert(2,7);

print("After Task 3.4 insert (listIntfillRange) = " + listIntfillRange.join(","));

listIntfillRange.insertAll(2, listIntAdd2);

print("After Task 3.4 insertAll (listIntfillRange) with (listIntAdd2) = " + listIntfillRange.join(","));
}

Image 2

For second code demonstration, I would be discussing setAll(int index, Iterable<E> iterable) /setRange(int start, int end, Iterable<E> iterable, [ int skipCount = 0 ]) ,take(int count)/takeWhile(bool test(E value)) ,fold<T>(T initialValue, T combine(T previousValue, E element)) ,remove(Object value)/removeAt(int index)/removeLast() ,removeRange(int start, int end), these are coded in listadd2() of listadd.dart.

C#
void listadd2()
{

//-- this list will contain 1,2,3,4,5
List<int> listIntAdd = new List<int>.generate(5,(int index)=>index+1,growable: true);

// this list will contain all zero
List<int> listIntAdd2 = new List<int>.generate(5,(int index)=>0,growable: true);


//Task3.5 setAll
print("Task 3.5 Before setAll (listIntAdd2) = " + listIntAdd2.join(","));

listIntAdd2.setAll(0, listIntAdd);
print("Task 3.5 After setAll (listIntAdd2) = " + listIntAdd2.join(","));

//Task 3.6 take/takeWhile

print("Task 3.6 take (listIntAdd2) = " + listIntAdd2.take(3).join(","));
// this will take element which is smaller than 4
print("Task 3.6 takeWhile (smaller than 4) (listIntAdd2) = 
      " + listIntAdd2.takeWhile((int item) => item <= 3 ).join(","));

//Task 3.7 fold, here we will calculate sum of all element

print("Task 3.7 fold (listIntAdd2) Initial Val= " + listIntAdd2.join(","));

// here I used toString to convert resulting integer to string to be displayed with print

print("Task 3.7 fold (listIntAdd2) = " + listIntAdd2.fold(0, (prev,element)=>prev+element).toString());

//Task 3.9 remove,removeAt,removeLast

print("Task 3.9 (listIntAdd2) Initial Val= " + listIntAdd2.join(","));

//remove 5 from listIntAdd2

listIntAdd2.remove(5);
print("Task 3.9 remove (listIntAdd2) = " + listIntAdd2.join(","));

//remove from post 2 from listIntAdd2

listIntAdd2.removeAt(2);
print("Task 3.9 removeAt (listIntAdd2) = " + listIntAdd2.join(","));

//removeLast from listIntAdd2

listIntAdd2.removeLast();
print("Task 3.9 removeAt (listIntAdd2) = " + listIntAdd2.join(","));


//Task 3.10 removeRange remove first two element from list

print("Task 3.10 (listIntAdd) Initial Val= " + listIntAdd.join(","));
listIntAdd.removeRange(0, 2);
print("Task 3.10 removeAt (listIntAdd) = " + listIntAdd.join(","));
}

Image 3

Here, we reached the end of Task #3.

Task#4

In the following code, I am going to discuss indexOf(E element, [ int start = 0 ]),elementAt(int index),lastIndexOf(E element, [ int start ]),any(bool f(E element)),sublist(int start, [ int end ]),where(bool test(E element)). The example is present in listwhere() function of where.dart.

C#
listwhere(){

//-- this list will contain 1,2,3,4,5,6,7,8

List<int> listIntWhere= new List<int>.generate(8,(int index)=>index+1,growable: true);

// Task 4.1 indexOf, let find index of 6, it should be 5th, as list is zero based

print("Task 4.1 indexOf (listIntWhere) InitialVal= " + listIntWhere.join(","));
print("Task 4.1 indexOf (listIntWhere)= " + listIntWhere.indexOf(6).toString());

// Task 4.2 elementAt, let find element at 5th, it should be 6, as list is zero based

print("Task 4.2 elementAt (listIntWhere) InitialVal= " + listIntWhere.join(","));
print("Task 4.2 elementAt (listIntWhere)= " + listIntWhere.elementAt(5).toString());

// Task 4.3 lastIndexOf, let create new list with duplicate value
// it will contain 0,1,2,0,1,2

List<int> listDuplicate = new List.generate(6, (int x)=> x<3?x:x-3);
print("Task 4.3 lastIndexOf (listDuplicate) InitialVal= " + listDuplicate.join(","));
print("Task 4.3 lastIndexOf (listDuplicate)= " + listDuplicate.lastIndexOf(1).toString());


// Task 4.4 any, let find does list contain item 2

print("Task 4.4 any (listDuplicate) InitialVal= " + listDuplicate.join(","));
print("Task 4.4 any (listDuplicate)= " + listDuplicate.any((int item)=>item==2).toString());

// Task 4.5 sublist, let create sublist from 3 to 6 item

print("Task 4.5 sublist (listDuplicate) InitialVal= " + listDuplicate.join(","));
print("Task 4.5 sublist (listDuplicate)= " + listDuplicate.sublist(3,6).join(","));

// Task 4.6 where, let find item divisible by 2

print("Task 4.6 where (listDuplicate) InitialVal= " + listDuplicate.join(","));
print("Task 4.6 where (listDuplicate)= " + listDuplicate.where((int item)=> item%2==0).join(","));
}

Image 4

Last but not the least, in the following code, I am going to discuss singleWhere(bool test(E element)) ,firstWhere(bool test(E element), { E orElse() }),lastWhere(bool test(E element), { E orElse() }) ,retainWhere(bool test(E element)),removeWhere(bool test(E element)) . The example is present in listwhere2() function of where.dart.

C#
listwhere2(){

//-- this list will contain 1,2,3,4,5,6,7,8
List<int> listIntWhere= new List<int>.generate(8,(int index)=>index+1,growable: true);

// Task 4.7 singleWhere, lets find single element in the list
print("Task 4.7 singleWhere (listIntWhere) InitialVal= " + listIntWhere.join(","));
print("Task 4.7 after singleWhere (listIntWhere)= " + 
    listIntWhere.singleWhere((int item)=>item==2).toString());

try{
listIntWhere.singleWhere((int item)=>item==9);
}
catch(ex)
{
print("Task 4.7 after singleWhere (listIntWhere) (from catch) notFound = " + ex.toString());
}

// Task 4.8 firstWhere, advantage of firstWhere is that you can specify the default element
// in case element not found
// create the list, it will contain 0,1,2,3,0,1,2,3

List<int> listDuplicate = new List.generate(8, (int x)=> x<4?x:x-4);
print("Task 4.8 firstWhere (listDuplicate) InitialVal= " + listDuplicate.join(","));
print("Task 4.8 after firstWhere (listDuplicate)= " + 
listDuplicate.firstWhere((int item)=>item==2).toString());
print("Task 4.8 after firstWhere (listDuplicate) notFound (return -1)= " + 
listDuplicate.firstWhere((int item)=>item==10,orElse: ()=>-1).toString());

// Task 4.9 lastWhere, advantage of lastWhere is that you can specify the default element
// in case element not found

print("Task 4.9 lastWhere (listDuplicate) InitialVal= " + listDuplicate.join(","));
print("Task 4.9 after lastWhere (listDuplicate)= " + 
    listDuplicate.lastWhere((int item)=>item==2).toString());
print("Task 4.9 after lastWhere (listDuplicate) notFound (return -1)= " + 
    listDuplicate.lastWhere((int item)=>item==10,orElse: ()=>-1).toString());

// Task 4.10 retainWhere, retain element in list that is divisible by 2

print("Task 4.10 retainWhere (listDuplicate) InitialVal= " + listDuplicate.join(","));
listDuplicate.retainWhere((int x)=> x%2==0);
print("Task 4.10 after retainWhere (listDuplicate) = " + listDuplicate.join(","));

// Task 4.11 removeWhere, remove element in list that is not divisible by 2

print("Task 4.11 removeWhere (listIntWhere) InitialVal= " + listIntWhere.join(","));
listIntWhere.removeWhere((int x)=> x%2!=0);
print("Task 4.11 after removeWhere (listIntWhere) = " + listIntWhere.join(","));
}

Image 5

Here, we reached the end of Task #4.

Points of Interest

Flutter Tutorial

  1. Flutter Getting Started: Tutorial #1
  2. Flutter Getting Started: Tutorial 2 - StateFulWidget

DART Series

  1. DART2 Prima Plus - Tutorial 1

History

  • 08-July-2018: First version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)