Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

basics
dart
array

How to create an array in Dart

Educative Answers Team

An array is an object used to store a collection of values. This collection could be anything: numbers, objects, more arrays, etc.

In Dart, arrays are used to store multiple values in one variable. Each value can be accessed through an index (starts from zero). The values stored in an array are called elements.

svg viewer

Initializing arrays in Dart

There are multiple ways to initialize arrays in Dart:

1. Using the literal constructor

A new array can be created by using the literal constructor []:

import 'dart:convert';
void main() { 
   var arr = ['a','b','c','d','e']; 
   print(arr); 
}

2. Using the new keyword

An array can also be created using new along with arguments:

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); 
}

A few commonly used methods

Method Description
first() It returns the first element of the array.
last() It returns the last element of the array.
isEmpty() It returns true if the list is empty; otherwise, it returns false.
length() It returns the length of the array.
import 'dart:convert';
void main() { 
   var arr = ['a','b','c','d','e']; 
   print(arr.first);// first element of array
   print(arr.last);// last element of array
   print(arr.isEmpty);// to check whether the array is empty or not
   print(arr.length);// the lenght of the array
   
}

RELATED TAGS

basics
dart
array
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring