DART2 Prima Plus - Tutorial 2 - LIST
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.
- Task#1 Creation
List(int length)
- Create a list of the givenlength
List.filled(int length,E fill,{bool growable:false})
- Create a fixed length list of the givenlength
and initialise the value of each position withfill
argumentList.generate(int length, E generator(int index),{bool gowable:true}
) - generate a list of values based ongenerator
function based onlength
argumentList.unmodifable(Iterable elements)
- Create an unmodifiable list containing all elements.List.from(Iterable elements,{bool growable:false})
- Create a list containing all the elements.static List.copyRange<T>(List<T> target, int at, List<T> source, [int start, int end])
: copysource
list totarget
, starting fromat
, you can also specifystart
(inclusive) andend
(exclusive) of source list to copy.
- Task#2 Properties
first
- Return first element from listlast
- Return last element from listlength
- Return length of listreversed
- Reverse the listisEmpty
- Check if the list is emptyisNotEmpty
- Check if the list is non-emptyruntimeType
- Object type, similar to type in C#
- Task#3 Add/Delete Data
add(E value), addAll(Iterable<E> iterable)
- Add Value/iterable to listasMap()
- Returns an unmodifiable Map of list, key would beindex
, and list item asvalue
fillRange(int start, int end, [ E fillValue ])
/Iterable<E> getRange(int start, int end)
- Sets the objects in the rangestart
inclusive toend
exclusive to the givenfillValue
/ Returns an Iterable that iterates over the objects in the rangestart
inclusive toend
exclusive.insert(int index, E element)/ insertAll(int index, Iterable<E> iterable)
- Inserts the object at positionindex
in this list / Inserts all objects ofiterable
at positionindex
in this list & Inserts all objects ofiterable
at positionindex
in this list.setAll(int index, Iterable<E> iterable) /setRange(int start, int end, Iterable<E> iterable, [ int skipCount = 0 ])
- Copies the objects ofiterable
, skippingskipCount
objects first, into the rangestart
, inclusive, toend
, exclusive, of the list.take(int count)/takeWhile(bool test(E value)
) - Returns a lazy iterable of thecount
first elements of this iterable. / Returns a lazy iterable of the leading elements satisfyingtest
.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 valuejoin([String separator = "" ])
- Converts each element to a String and concatenates thestring
sremove(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.removeRange(int start, int end)
- Removes the objects in the range start inclusive to end exclusive.
- Task#4 Find and where is data
indexOf(E element, [ int start = 0 ])
- Returns the first index ofelement
in this list.elementAt(int index)
- Returns the indexth element.lastIndexOf(E element, [ int start ])
- Returns the last index of element in this list.any(bool f(E element))
- Checks whether any element of this iterable satisfies test.sublist(int start, [ int end ])
- Returns a new list containing the objects from start inclusive to end exclusive.where(bool test(E element))
- Returns a new lazy Iterable with all elements that satisfy the predicate test.singleWhere(bool test(E element))
- Returns the single element that satisfies test.firstWhere(bool test(E element), { E orElse() })
- Returns the first element that satisfies the given predicate test.lastWhere(bool test(E element), { E orElse() })
- Returns the last element that satisfies the given predicate test.retainWhere(bool test(E element))
- Removes all objects from this list that fail to satisfy testremoveWhere(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.
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.
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}");
}
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
.
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(","));
}
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
.
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(","));
}
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
.
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(","));
}
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
.
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(","));
}
Here, we reached the end of Task #4.
Points of Interest
- Language specification: http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-408.pdf
- Dart website: https://www.dartlang.org/
- Article GitHub: https://github.com/thatsalok/FlutterExample/tree/master/darttutorial2
Flutter Tutorial
DART Series
History
- 08-July-2018: First version