What is Dart Lists & How many types of Lists in dart?

  • Consider a situation where we need to store five String values. If we use programming’s simple variable and data type concepts, then we need five variables of String data type.
  • It seems simple because we had to store just five String values. Now let’s assume we have to store 10000 String values. Now its too much time consuming to create 10000 variables.
  • To overcome this kind of situations we have a concept called Collections.
  • Collections are used to store data.

In dart, collections can be classified into four basic categories:

  1. List
  2. Map
  3. Set
  4. Queue
  • But the list and map are mostly used. Set and queue are used in some special cases.

List

  • The list is a collection of data having the same data type. In other languages List is called Array.
  • In list, data is stored in an ordered way.
  • Every individual element of the list can be accessed by its index number. The index number always starts from 0.

There are two types of list:

  1. Fixed length list
  2. Growable list

Fixed Length List

  • In the fixed length list once the length of the list is defined it cannot be changed during run time.

Syntax

List <data type> list_name = List (length of list);

Example:

main() {
  List<int> marks = List(5);
  marks[0] = 25;    // Inserting values to list
  marks[1] = 35;
  marks[2] = 65;
  marks[3] = 75;
  marks[4] = 63;

  for (int elements in marks) {
    print(elements);
  }
}

Output
25
35
65
75
63

Growable List

  • The length of Growable list is dynamic. It can be changed during run time.

Syntax

List <data type> list_name = List (); // Way 1
List <data type> list_name = [element1, element2]; // Way 2

Example:

main() {

  List<String> countries = ["India", "Nepal"];
  for (String elements in countries) {
    print(elements);
  }
}

Output
India
Nepal

List Properties

The following table lists some commonly used properties of the List class in the dart:core library.

Sr.NoMethods & Description
1first Returns the first element in the list.
2isEmpty Returns true if the collection has no elements.
3isNotEmpty Returns true if the collection has at least one element.
4length Returns the size of the list.
5last Returns the last element in the list.
6reversed Returns an iterable object containing the lists values in the reverse order.
7Single Checks if the list has only one element and returns it.

Some Other useful Methods of List in Dart :

sublist():

This method returns a new list containing elements from index between start and end. Note that end element is exclusive while start is inclusive.

 var myList= [1,2,3,4,5];
print(myList.sublist(1,3)); // [2,3]

If end parameter is not provided, it returns all elements starting from start till length of the list.

print(myList.sublist(1)); // [2,3,4,5]

shuffle():

This method re-arranges order of the elements in the given list randomly.

 myList.shuffle();
print('$myList'); // [5,4,3,1,2]

reversed:

reversed is a getter which reverses iteration of the list depending upon given list order.

 var descList= [6,5,4,3,2,1];
print(descList.reversed.toList()); // [1,2,3,4,5,6]

var ascList = [1,2,3,4,5,6];
print(ascList.reversed.toList()); // [6,5,4,3,2,1]

asMap():

This method returns a map representation of the given list. The key would be the indices and value would be the corresponding elements of the list.

 List<String> sports = ['cricket', 'football', 'tennis', 'baseball'];
Map<int, String> map = sports.asMap();
print(map); // {0: cricket, 1: football, 2: tennis, 3: baseball}

whereType():

This method returns iterable with all elements of specific data type.

Let’s say we have a list with mix data such as String and int and we just want to retrieve int data from it, then we would use whereType method as:

 var mixList = [1, "a", 2, "b", 3, "c", 4, "d"];
var num = mixList.whereType<int>();
print(num); // (1, 2, 3, 4)

Similarly, we can retrieve only String data by specifying mixList.whereType<String>();

getRange():

This method returns elements from specified range [start] to [end] in same order as in the given list. Note that, start element is inclusive but end element is exclusive.

 var myList = [1, 2, 3, 4, 5];
print(myList.getRange(1,4)); // (2, 3, 4)

replaceRange():

This method helps to replace / update some elements of the given list with the new ones. The start and end range need to be provided alongwith the value to be updated in that range.

 var rList= [0,1,2,3,4,5,6];
rList.replaceRange(2,3, [10]);
print('$rList'); // [0, 1, 10, 3, 4, 5, 6]

firstWhere():

This method returns the first element from the list when the given condition is satisfied.

var firstList = [1,2,3,4,5,6];
print(firstList.firstWhere((i) => i < 4)); // 1

var sList = ['one', 'two', 'three', 'four'];
print(sList.firstWhere((i) => i.length > 3)); // three

Similarly, lastWhere() returns last element from the list when given condition is met. where() returns new list that matches the condition.

singleWhere():

This method returns the first matching element from the list when there’s an exact match.

 var mList = [1, 2, 3, 4];
print(mList.singleWhere((i) => i == 3)); // 3

If the given list contains a duplicate, then singleWhere method retuns an exception. In that case, we can use firstWhere method which returns the first matching element irrespective of repeating / duplicates in the list.

 var sList = [1, 2, 3, 3, 4];
print(sList.singleWhere((i) => i == 3)); // Bad state: Too many elements

print(sList.firstWhere((i) => i == 3)); // 3

fold():

This method returns a single value by iterating all elements of given list along with an initialValue , ie, if we want sum of all elements or product of all elements, then, fold helps us to do that.

 var lst = [1,2,3,4,5];
var res = lst.fold(5, (i, j) => i + j);
print('res is ${res}'); // res is 20

In above example, 5 is the initialValue and then fold starts the iteration from index 0, adds element to the initialValue (5 + 1) and moves ahead till index 4 like (6+2, 8+3, 11+4, 15+5). Hence, the single value, ie sum of all elements + intialValue is returned as 20.

reduce():

This method is very similar to fold and returns a single value by iterating all elements of given list. Only difference is, this method doesn’t take any initialValue and the given list should be non-empty.

 var lst = [1,2,3,4,5];
var res = lst.reduce((i, j) => i + j);
print('res is ${res}'); // res is 15

followedBy():

This method appends new iterables to the given list.

var sportsList = ['cricket', 'tennis', 'football'];
print(sportsList.followedBy(['golf', 'chess']).toList()); // [cricket, tennis, football, golf, chess]

any():

This method returns a boolean depending upon whether any element satisfies the condition or not.

print(sportsList.any((e) => e.contains('cricket'))); // true

every():

This method returns a boolean depending upon whether all elements satisfies the condition or not.

print(sportsList.every((e) => e.startsWith('a'))); // false

take():

This method returns iterable starting from index 0 till the count provided from given list.

print(sportsList.take(2));  // (cricket, tennis)

skip():

This method ignores the elements starting from index 0 till count and returns remaining iterable from given list.

print(sportsList.skip(2));  // (football)

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More