dart list code example
Example 1: declaring and initializing a list in dart
import 'dart:core';
void main() {
//List of integers
List intArr = [1,2,3,4,5];
print(intArr);
//List of strings
List strArr = ['hello', 'world'];
print(strArr);
}
Example 2: inserting elements to integer array dart
import 'dart:core';
void main() {
List intArr = [1,2,3,4,5];
//adding single int to list
intArr.add(6);
//adding multiple int to list
intArr.addAll([7,8]);
//adding element or elements to specific location
//syntax: List.insert(index,value)
intArr.insert(0,0);
//syntax: List.insertAll(index, iterable_list_of _values)
intArr.insertAll(0,[-2,-1]);
}
Example 3: dart have array
import 'dart:convert';
void main() {
var arr = new List(5);// creates an empty array of length 5
// assigning values to all the indices
arr[0] = 'a';
arr[1] = 'b';
arr[2] = 'c';
arr[3] = 'd';
arr[4] = 'e';
print(arr);
}
Example 4: list dart
var fixedLengthList = List.filled(5, 0);
fixedLengthList.length = 0; // Error
fixedLengthList.add(499); // Error
fixedLengthList[0] = 87;
var growableList = [1, 2];
growableList.length = 0;
growableList.add(499);
growableList[0] = 87;
Example 5: get single element from list in dart
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