Array in dart

Array in dart DEFAULT
How to print array in flutter

Hi Guys, Welcome to Proto Coders Point, In this tutorial we will learn about arrays in dart flutter with an example

What is array in dart?

Same as other programming language, In dart also the defination of array is same.

An array in an object that can be used to store a list of collections of elements. In array list the collection can be of any datatype: numbers, String, etc.

In Flutter dart, array can be used to store multiple values in one datatype variable.

To access the value/element in the array list then you can do it through it index id.
The value stored in an array are called as elements.

array in dart flutter

Initializing arrays in Dart

Using literal constructor

Using Literal constructor [] an new array can be created: as shown in below example:

import 'dart:convert'; void main() { var arr = ['a','b','c','d','e']; // array literal constructor print(arr); //print the array on the screen }

How to print array in flutter?

To print array list on the screen or on console log then

you can make use of print cmd to print on console

else if you want to display array in your flutter app then you can make use of Text widget to show the array list

 new keyword and List 

import 'dart:convert'; void main() { var arr = new List(5);// creates an empty array of length 5 // assigning values to all the indices //adding data to array list arr[0] = 'a'; arr[1] = 'b'; arr[2] = 'c'; arr[3] = 'd'; arr[4] = 'e'; print(arr); }

How to access particular array element? Method to read array list

Return first element of the array.
 last element of the array.
It returns  if the list is empty; otherwise, it returns .
It returns the length of the array. eg : 5


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 }

Rajat Palankar

I am a tech geek who likes to contribute to society by continuously spreading his knowledge to you guys, I have Completed my “Master’s of the computer application ( M.C.A )” from Gogte Institute of Technology, Belgaum, I love to share my technical knowledge by writing programming blogs, I even like to use new tech Gadgets. I am interested mostly in Mobile Application Development mostly on Android and currently beginner in Flutter Development.


Dart Programming - Lists

A very commonly used collection in programming is an array. Dart represents arrays in the form of List objects. A List is simply an ordered group of objects. The dart:core library provides the List class that enables creation and manipulation of lists.

The logical representation of a list in Dart is given below −

Logical Representation of a List
  • test_list − is the identifier that references the collection.

  • The list contains in it the values 12, 13, and 14. The memory blocks holding these values are known as elements.

  • Each element in the List is identified by a unique number called the index. The index starts from zero and extends up to n-1 where n is the total number of elements in the List. The index is also referred to as the subscript.

Lists can be classified as −

  • Fixed Length List
  • Growable List

Let us now discuss these two types of lists in detail.

Fixed Length List

A fixed length list’s length cannot change at runtime. The syntax for creating a fixed length list is as given below −

Step 1 − Declaring a list

The syntax for declaring a fixed length list is given below −

var list_name = new List(initial_size)

The above syntax creates a list of the specified size. The list cannot grow or shrink at runtime. Any attempt to resize the list will result in an exception.

Step 2 − Initializing a list

The syntax for initializing a list is as given below −

lst_name[index] = value;


Live Demo void main() { var lst = new List(3); lst[0] = 12; lst[1] = 13; lst[2] = 11; print(lst); }

It will produce the following output

[12, 13, 11]

Growable List

A growable list’s length can change at run-time. The syntax for declaring and initializing a growable list is as given below −

Step 1 − Declaring a List

var list_name = [val1,val2,val3] --- creates a list containing the specified values OR var list_name = new List() --- creates a list of size zero

Step 2 − Initializing a List

The index / subscript is used to reference the element that should be populated with a value. The syntax for initializing a list is as given below −

list_name[index] = value;


The following example shows how to create a list of 3 elements.

Live Demo void main() { var num_list = [1,2,3]; print(num_list); }

It will produce the following output

[1, 2, 3]


The following example creates a zero-length list using the empty List() constructor. The add() function in the List class is used to dynamically add elements to the list.

Live Demo void main() { var lst = new List(); lst.add(12); lst.add(13); print(lst); }

It will produce the following output

[12, 13]

List Properties

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

Sr.NoMethods & Description

Returns the first element in the list.


Returns true if the collection has no elements.


Returns true if the collection has at least one element.


Returns the size of the list.


Returns the last element in the list.


Returns an iterable object containing the lists values in the reverse order.


Checks if the list has only one element and returns it.

  1. 12x24 garage shed
  2. Buy megaphone in store
  3. Alpha coders
  4. Fold up bathtub
(This is Part 3 in a series about Dart. Check out Part 2, Function in Dart.)

Warning: We expect the Dart libraries to undergo potentially sweeping changes before Dart goes to alpha. This document is relevant as of 2011-12-22.


Dart is a "batteries included" effort to help app developers build modern web apps. An important "battery" is the bundled core Dart libraries, providing common and rich functionality. Dart is building a solution for large, complex web apps, and providing well tested, integrated, and common libraries is key to helping a web app developer be more productive out of the box.

The Collection libraries are a crucial set of APIs that Dart developers get for free. Much more than simple arrays and maps, the Collection library includes standard ways to filter, iterate, inspect, compose, and sort your data. This post specifically looks at List<E>, Dart's ordered, indexable collection of objects.

Aside: The Dart project is lucky to welcome Josh Bloch to the team, who will be leading the library design efforts. Expect some great things for the libraries and Dart!

Arrays are Lists

Perhaps the most common collection in nearly every programming language is the array, or ordered set of objects. Dart arrays are Lists, so look for Listin the documentation. A Dart List will compile to a JavaScript array.

Fun fact: As of 2011-12-22, the word "array" does not appear in the Dart spec.

List basics

Dart supports List literals like JavaScript. A simple Dart list:

Get the list's length, or number of elements inside of the list:

Access the second element in the list: (notice how Dart list indexes are 0 based, i.e. 0 is the first element, 1 is the second element, etc)

If you try to reference an element that is outside the length of the list, you'll get an IndexOutOfRangeException.

Add an element to a list constructed from a list literal:

Now is a good time to point out that the add(object)method is optional. That is, not all implementations of List have to support it. I don't personally like optional methods, but this is where we stand as of 2011-12-22.

An example of a List that you can't add to is the fixed size List, as constructed by:

Unfortunately, the docs right now don't clue you in that the new List(size) constructor returns a fixed size List, but follow bug 948for the comment fix.

It's important to know that when you construct a fixed size List, that the List itself is allocated to that size and filled with nulls for the size of the List. For example:

Also important to know for JavaScript developers: Lists in Dart are not associative arrays. That is, the following code will NOT work in Dart:

Remove an element from a list: (I know, I know, we're lacking a simple removeAt(index) function (see bug 947). See comment about Josh Bloch above and just hang tight :)

To print the elements of a List, we need to add a map()function to eventually convert a Listto a List<String>because Strings.joinonly takes a List<String>. The Dart libs are lacking a map function on collections (see bug  945).


Sorting a List takes advantage of Dart's function support.


Iterating over a List can be done in at least four ways. The standard, most familiar way is the forloop:

There's a more terse way of using forif you don't need the current iteration index:

The verbose way to say the above is to use a formal Iteratorfrom the List:

And finally, if you just want to apply a function to each element of the List, use forEach:


The Collection interface, which List extends, provides a filter method, which returns a new collection with only the elements that satisfy a condition.

An example of filtering:

Of course, you don't need to inline the filtering function. Passing in a function also works:

Next steps

Check out the every(bool f(E element))and some(bool f(E element))methods to check if the List matches every condition or at least one condition, respectively.

Of course, please review the full Collection<E>docs and the List<E>docs.


Dart has Lists which are ordered sequences of objects. There is no class or interface called Array, though Lists act extremely similar to Arrays you might have encountered in other programming languages.

Dart Lists are not associative arrays like JavaScript, but Dart does have list literals for easy declaration.

The core Dart libraries will almost certainly undergo sweeping changes now that Josh Bloch has joined the team. For now, though, there's still a lot you can do with Dart's lists. As you work with the libraries, remember that Dart is in Technology Preview mode, and we really want to hear your feedback.

What do you need from the libraries? Let us know at the mailing listor please file an issue. Thanks!

Next steps

Check out Part 4: Maps and hashes in Dart.
10 Must Know Dart Array Methods

An indexable collection of objects with a length.

Subclasses of this class implement different kinds of lists. The most common kinds of lists are:

  • Fixed-length list. An error occurs when attempting to use operations that can change the length of the list.

  • Growable list. Full implementation of the API defined in this class.

The default growable list, as created by , keeps an internal buffer, and grows that buffer when necessary. This guarantees that a sequence of add operations will each execute in amortized constant time. Setting the length directly may take time proportional to the new length, and may change the internal capacity so that a following add operation will need to immediately increase the buffer capacity. Other list implementations may have different performance behavior.

The following code illustrates that some List implementations support only a subset of the API.

Lists are Iterable. Iteration occurs over values in index order. Changing the values does not affect iteration, but changing the valid indices—that is, changing the list's length—between iteration steps causes a ConcurrentModificationError. This means that only growable lists can throw ConcurrentModificationError. If the length changes temporarily and is restored before continuing the iteration, the iterator might not detect it.

It is generally not allowed to modify the list's length (adding or removing elements) while an operation on the list is being performed, for example during a call to forEach or sort. Changing the list's length while it is being iterated, either by iterating it directly or through iterating an Iterable that is backed by the list, will break the iteration.

Implemented types


Creates a list of the given length. [...]


List.empty({boolgrowable = false})
Creates a new empty list. [...]


List.filled(intlength, Efill, {boolgrowable = false})
Creates a list of the given length with at each position. [...]


List.from(Iterableelements, {boolgrowable = true})
Creates a list containing all . [...]


List.generate(intlength, Egenerator(intindex), {boolgrowable = true})
Generates a list of values. [...]


List.of(Iterable<E>elements, {boolgrowable = true})
Creates a list from . [...]


Creates an unmodifiable list containing all . [...]



first↔ E
Returns the first element. [...]

read / write, inherited-getter

hashCode→ int
The hash code for this object. [...]

read-only, inherited

isEmpty→ bool
Returns if there are no elements in this collection. [...]

read-only, inherited

isNotEmpty→ bool
Returns true if there is at least one element in this collection. [...]

read-only, inherited

iterator→ Iterator<E>
Returns a new that allows iterating the elements of this . [...]

read-only, inherited

last↔ E
Returns the last element. [...]

read / write, inherited-getter

length↔ int
The number of objects in this list. [...]

read / write

reversed→ Iterable<E>
An Iterable of the objects in this list in reverse order.


runtimeType→ Type
A representation of the runtime type of the object.

read-only, inherited

single→ E
Checks that this iterable has only one element, and returns that element. [...]

read-only, inherited


add(Evalue) → void
Adds to the end of this list, extending the length by one. [...]
addAll(Iterable<E>iterable) → void
Appends all objects of to the end of this list. [...]
any(booltest(Eelement)) → bool
Checks whether any element of this iterable satisfies . [...]


asMap() → Map<int, E>
An unmodifiable Map view of this list. [...]
cast<R>() → List<R>
Returns a view of this list as a list of instances. [...]


clear() → void
Removes all objects from this list; the length of the list becomes zero. [...]
contains(Object?element) → bool
Whether the collection contains an element equal to . [...]


elementAt(intindex) → E
Returns the th element. [...]


every(booltest(Eelement)) → bool
Checks whether every element of this iterable satisfies . [...]


expand<T>(Iterable<T>toElements(Eelement)) → Iterable<T>
Expands each element of this Iterable into zero or more elements. [...]


fillRange(intstart, intend, [E?fillValue]) → void
Overwrites a range of elements with . [...]
firstWhere(booltest(Eelement), {EorElse()?}) → E
Returns the first element that satisfies the given predicate . [...]


fold<T>(TinitialValue, Tcombine(TpreviousValue, Eelement)) → T
Reduces a collection to a single value by iteratively combining each element of the collection with an existing value [...]


followedBy(Iterable<E>other) → Iterable<E>
Returns the lazy concatenation of this iterable and . [...]


forEach(voidaction(Eelement)) → void
Invokes on each element of this iterable in iteration order.


getRange(intstart, intend) → Iterable<E>
Creates an Iterable that iterates over a range of elements. [...]
indexOf(Eelement, [intstart = 0]) → int
The first index of in this list. [...]
indexWhere(booltest(Eelement), [intstart = 0]) → int
The first index in the list that satisfies the provided . [...]
insert(intindex, Eelement) → void
Inserts at position in this list. [...]
insertAll(intindex, Iterable<E>iterable) → void
Inserts all objects of at position in this list. [...]
join([Stringseparator = ""]) → String
Converts each element to a String and concatenates the strings. [...]


lastIndexOf(Eelement, [int?start]) → int
The last index of in this list. [...]
lastIndexWhere(booltest(Eelement), [int?start]) → int
The last index in the list that satisfies the provided . [...]
lastWhere(booltest(Eelement), {EorElse()?}) → E
Returns the last element that satisfies the given predicate . [...]


map<T>(TtoElement(Ee)) → Iterable<T>
The current elements of this iterable modified by . [...]


noSuchMethod(Invocationinvocation) → dynamic
Invoked when a non-existent method or property is accessed. [...]


reduce(Ecombine(Evalue, Eelement)) → E
Reduces a collection to a single value by iteratively combining elements of the collection using the provided function. [...]


remove(Object?value) → bool
Removes the first occurrence of from this list. [...]
removeAt(intindex) → E
Removes the object at position from this list. [...]
removeLast() → E
Removes and returns the last object in this list. [...]
removeRange(intstart, intend) → void
Removes a range of elements from the list. [...]
removeWhere(booltest(Eelement)) → void
Removes all objects from this list that satisfy . [...]
replaceRange(intstart, intend, Iterable<E>replacements) → void
Replaces a range of elements with the elements of . [...]
retainWhere(booltest(Eelement)) → void
Removes all objects from this list that fail to satisfy . [...]
setAll(intindex, Iterable<E>iterable) → void
Overwrites elements with the objects of . [...]
setRange(intstart, intend, Iterable<E>iterable, [intskipCount = 0]) → void
Writes some elements of into a range of this list. [...]
shuffle([Random?random]) → void
Shuffles the elements of this list randomly.
singleWhere(booltest(Eelement), {EorElse()?}) → E
Returns the single element that satisfies . [...]


skip(intcount) → Iterable<E>
Returns an Iterable that provides all but the first elements. [...]


skipWhile(booltest(Evalue)) → Iterable<E>
Returns an that skips leading elements while is satisfied. [...]


sort([intcompare(Ea, Eb)?]) → void
Sorts this list according to the order specified by the function. [...]
sublist(intstart, [int?end]) → List<E>
Returns a new list containing the elements between and . [...]
take(intcount) → Iterable<E>
Returns a lazy iterable of the first elements of this iterable. [...]


takeWhile(booltest(Evalue)) → Iterable<E>
Returns a lazy iterable of the leading elements satisfying . [...]


toList({boolgrowable = true}) → List<E>
Creates a List containing the elements of this Iterable. [...]


toSet() → Set<E>
Creates a Set containing the same elements as this iterable. [...]


toString() → String
A string representation of this object. [...]


where(booltest(Eelement)) → Iterable<E>
Returns a new lazy Iterable with all elements that satisfy the predicate . [...]


whereType<T>() → Iterable<T>
Returns a new lazy Iterable with all elements that have type . [...]



operator +(List<E>other) → List<E>
Returns the concatenation of this list and . [...]
operator ==(Objectother) → bool
Whether this list is equal to . [...]


operator [](intindex) → E
The object at the given in the list. [...]
operator []=(intindex, Evalue) → void
Sets the value at the given in the list to . [...]

Static Methods

castFrom<S, T>(List<S>source) → List<T>
Adapts to be a . [...]


copyRange<T>(List<T>target, intat, List<T>source, [int?start, int?end]) → void
Copy a range of one list into another list. [...]
writeIterable<T>(List<T>target, intat, Iterable<T>source) → void
Write the elements of an iterable into a list. [...]

Dart array in

How to Create Use an Array in Flutter Dart Example Tutorial

Array is used to hold similar type of multiple values in single object. Each value is assigned with a index number position. The first element of array is located at 0 number index position and so on the next element is on 1 Index next is on Third index number. In Flutter to store multiple value we have to use Array. In array each value can be accessed via Index position. The items store in array are known as Array Elements. So in this tutorial we would learn about How to Create Use an Array in Flutter Dart Example Tutorial.

Screenshot of Array with random values :-

How to Create Use an Array in Flutter Dart Example Tutorial

There are by default two different methods available in Dart to initialize Array in dart. We would discuss both methods in this tutorial.

1. Creating Array Using Literal Constructor:

The first method of creating array is using Literal constructor [ ] . See the below code example for fully understand the coding technique.








2. Creating Array Using New List Keyword:

The second easiest way to create Array items using New keyword in Dart. Using this we can easily create List in dart. List with same values respond as Array in dart.



  // Creating Array with Six items.



   // Assigning values in Array on all Index.











#11.1 Dart Collections: Arrays or LIST as Fixed-length List. Dart for Flutter

“array.dart” Code Answer’s

declaring and initializing a list in dart

Dart answers related to “array.dart”

Dart queries related to “array.dart”

More “Kinda” Related Dart Answers View All Dart Answers »

  • listview.separated flutter
  • flutter delay
  • flutter wait for specific time
  • dart random number
  • dart regex for email
  • dart list map index
  • how to return a random number from a list in dart
  • flutter sleep
  • Waiting for another flutter command to release the startup lock...
  • Waiting for another flutter command to release the startup lock..
  • killl dart daemon
  • Waiting for another flutter command to release the startup loc
  • flutter get current date
  • dart regex for url
  • dart datetime parse
  • flutter datetime to string
  • parse string to datetime
  • flutter get millis time
  • dart string interpolation
  • dart datetime difference
  • how to do type casting in dart for string
  • how to find the type of object in dart
  • dart timestamp
  • java utils wait for seconds
  • target of uri doesn
  • pub.dec
  • New Year's Eve
  • loop in dart
  • flutter list sublist
  • dart round to 2 decimals
  • datetime dart format print
  • order list dart
  • extend class flutter
  • flutter check if string is number
  • flutter check if string is number dart
  • dart convert string to datetime
  • add years to date dart
  • addyears dart
  • Is there any callback to tell me when “build” function is done in Flutter?
  • flutter replace character in string
  • remove space from string dart
  • dart get String input from user
  • string to double fultter
  • dart variable in string
  • sleep in dart
  • dart string empty or null
  • not empty string check dart
  • getit flutter
  • flutter Insecure HTTP is not allowed by platform
  • bad state insecure http is not allowed flutter
  • dart The argument type 'String' can't be assigned to the parameter type 'Uri'
  • dart parameter type uri
  • flutter await uri
  • kill all dart processes flutter
  • kill dart process
  • kill task flutter
  • send params to stateful widget
  • if directory exists flutter
  • Flutter turn string to int
  • dart number types
  • dart number
  • delete shared preference flutter
  • flutter remove map
  • decode, encode base64 dart
  • dart print item # of a list
  • dart create id
  • sharedpreferences flutter
  • store key value data on disk flutter
  • flutter substring
  • sklearn rmse
  • switch case in dart
  • flutter firestore timestamp to datetime
  • target of uri doesn't exist: 'package:flutter/material.dart'. try creating the file referenced by the uri, or try using a uri for a file that does exist.
  • image from internet flutter
  • impage from web flutter
  • network image url
  • double 2 decimal places flutter
  • dart copywith
  • splite number in dart
  • flutter transform translate
  • dart try-catch
  • check exception type flutter
  • how to find the length a list in dart
  • how to compare two objects in flutter
  • flutter async initstate
  • flutter delay a function
  • flutter date time to timestamp
  • flutter singleton
  • StateError (Bad state: No element)
  • hive regiter adapter enum
  • dart reverse list
  • flutter capture image from camera
  • generate method o dart list
  • get file name from path dart
  • get file type from file path flutter
  • sort list descending from spesific maps key in dart
  • flutter random pick in list
  • flutter string contains
  • unable to locate android sdk flutter in windows
  • psycopg2
  • install getx
  • how to get value from user in dart
  • increase text size of Test flutter
  • dart extension
  • how to get the last values of a string dart
  • flutter circularprogressindicator
  • dart Absolute value
  • The constructor returns type 'Color' that isn't of expected type 'MaterialColor'.
  • filterchip flutter
  • Dart set list spread operator
  • remove file extension from path dart
  • flutter await http.get timeout
  • flutter on build complete
  • flutter linearprogressindicator value
  • flutter absorbpointer
  • dart update
  • flutter json to list
  • dart timer
  • dart timer repeat
  • dart timer delay
  • dart repeat function
  • flutter ignorepointer
  • invalid image svg data flutter
  • dart extension function
  • dart command to stop program
  • error: insufficient permissions for device: user in plugdev group; are your udev rules wrong?
  • foreach loop in list in dart
  • dartpad missing browser features
  • dart check if object has property
  • containskey dart
  • DartPad requires localStorage to be enabled
  • DartPad localStorage
  • dartpad missing browser localstorage
  • Attribute [email protected] value=(@mipmap/launcher_icon) from AndroidManifest.xml:17:9-45
  • flutter list splice
  • python change type of elements in list
  • dart enum
  • bloc observer
  • declaring and initializing a list in dart
  • reverse srring in dart
  • linearprogressindicator flutter
  • flutter image asset
  • convert iso date string into date and time string flutter
  • how to display current date time in flutter
  • dart json encode example
  • dart list to json
  • dart jsonencode
  • dart jsonencode list
  • dart compare two lists
  • must be immutable flutter
  • dart store unique values
  • flutter android x
  • Program type already present:$MyResultReceiver
  • error: cannot find symbol public class AssetProvider extends FileProvider
  • Execution failed for task ':app:checkDebugDuplicateClasses'. > A failure occurred while executing
  • The build failed likely due to AndroidX incompatibilities in a plugin. The tool is about to try
  • flutter check type of object
  • dart convert int to double
  • flutter weekdays
  • how to load gif in flutter
  • vscode dart
  • flutter check ios or android
  • timer in flutter
  • dart add two strings
  • dart comments
  • dart string remove first character
  • dart shuffle list
  • flutter string to date time
  • generate random int dart
  • foreach loop flutter
  • flutter for loop
  • flutter for loop array
  • dart foreach
  • dart for loop inside list
  • dart list remove item
  • string to double dart
  • dart parse boolean from string
  • int to string dart
  • dart try catch
  • dart exception
  • could not find dart in your flutter sdk. please run
  • dart setters
  • dart getter
  • getters and setters dart
  • flutter Execution failed for task ':app:packageDebug'.
  • dart Shader compilation error
  • shader compilation error errors
  • flutter date input field
  • datetimeoffset flutter
  • print dart
  • dart arrow
  • flutter build apk release target arm android
  • dart async
  • double to int flutter
  • dart callback function
  • dart callback function with parameter
  • how to update dart sdk version
  • DioError (DioError [DioErrorType.DEFAULT]: Converting object to an encodable object failed: Instance of
  • dartlang group array by key
  • dart try
  • flutter create my own future function
  • cast variable dart
  • flutter firebase_messaging 9 ios
  • inserting elements to list dart
  • inserting elements to integer array dart
  • dart sort list by date
  • how to get terminal http request time
  • get length of map flutter
  • get index of element in map dart
  • dart for in loop
  • how to convert timestamp to datetime in dart
  • flutter length of string
  • flutter glassmorphism
  • flutter delete file
  • how to put the Pi in dart
  • dart combine maps
  • flutter future return error
  • last element in list dart
  • flutter get last element of array
  • get last element in list dart
  • Flutter/Flutter.h' file not found flutter
  • dart list generate
  • sort list dart
  • modify item in list dart
  • flutter precacheimage
  • how to check whether a list in dart is empty or not
  • mobx flutter
  • dart double to int
  • XAMPP flutter CORS policy
  • flutter localhost xmlhttprequest error
  • xmlhttprequest error flutter
  • Flutter For In loop explained
  • convert future list to list dart
  • dart array split
  • removing element from integer array in dart
  • dart remove first item from list
  • dart loop through array
  • unable to update dart sdk. retrying
  • flutter get key from map
  • convert a list to string in flutter
  • dart loop
  • how to subtract dates in flutter
  • dart test expect assert fail
  • flutter hot reloading not working
  • dart multiline string
  • fluter check that date is greater than another date
  • dart regex
  • online dart compiler
  • how to launch url in flutter web
  • string to int in dart
  • array 2d dart
  • The argument type 'Wrap' can't be assigned to the parameter type 'List<Widget>
  • class in dart
  • remove first and last character from string dart
  • Unable to load asset: /storage/emulated/0/
  • dart this constructor
  • dart custom exception
  • dart key value pair list
  • flutter map key/value
  • flutter array filter
  • int.parse flutter
  • dart filter by attribute
  • convert long to date android
  • device_id flutter
  • print flutter objects
  • dart terbary
  • dart ternary
  • dart inline if else
  • dart ternary operator multiple
  • dart null aware operators
  • dart null aware
  • create a validator in flutter
  • what is the use of substring in flutter
  • Flutter get each letter from string
  • type '_InternalLinkedHashMap<DateTime, int>' is not a subtype of type 'Map<DateTime, double>'
  • dart const constructor
  • removing element from array in dart
  • cannot run with sound null safety because the following dependencies don't support null safety
  • validator flutter
  • convert timeofday to string flutter
  • convert string date to datetime and format
  • type '_Type' is not a subtype of type 'Widget'
  • at this point the state of the widget element tree is no longer stable. flutter
  • dart char is uppercase
  • flutter int max value
  • Map in dart
  • Try using 'as prefix' for one of the import directives, or hiding the name from all but one of the imports.dartambiguous_import
  • convert string to double flutter
  • how to convert text to double flutter
  • flutter create new map
  • android studio test dart code
  • android studio run code without emulator
  • android studio run app without emulator
  • android studio run dart without emulator
  • android studio dart without emulator
  • flutter download image from url
  • how to save local storage using flutter
  • flutter how to save data locally
  • flutter future
  • dart double question mark
  • pass by reference in dart
  • dart have array
  • async* dart
  • how to perform get request in flutter
  • flutter check internet connection
  • dart optional parameters
  • dart optional positional parameters
  • how to get isoCode based on location in flutter
  • aws ec2 upload file
  • dart input int
  • flutter check file size
  • dart list of maps
  • how to add image to flutter
  • flutter types class enum
  • flutter stuck at syncing files to device chrome
  • flutter stuck
  • flutter stop while running app
  • dart reverse a string
  • dart concatenate string
  • flutter create vertical list
  • list widget flutter
  • listview in flutter
  • flutter listView docs
  • list view example found
  • message yes or not in dart
  • flutter print type
  • if else dart example
  • list in dart
  • how to take integer input from user in dart
  • dart filter list
  • string to timeofday flutter
  • flutter image load
  • dart get number from string
  • dar initilize list with zero
  • regex dart
  • how to parse an array of json objects in flutter
  • bloc flutter
  • flutter delete directory
  • dart main function
  • Invalid argument(s): join(null, "bin", "cache", "dart-sdk"): part 0 was null, but part 1 was not.
  • flutter dateFormat
  • inr symbol in flutter
  • brew install sublime
  • data types in flutter
  • dart call constructor in constructor
  • flutter check if null
  • checking null in dart
  • dart spread
  • import package from github flutter
  • length of array in flutter
  • dart convert int string leading zeros
  • release apk not working flutter
  • convert date in flutter
  • random number dart with length 7
  • how to print data types in dart
  • dart find element in list
  • phone authentication firebase flutter
  • provider flutter
  • dart function
  • variables in dart
  • flutter list.generate
  • dart constructor assert
  • python websocket
  • how to obfuscate flutter code
  • obfuscate flutter code
  • obfuscating your app


Similar news:

A tour of the Dart language

This page shows you how to use each major Dart feature, from variables and operators to classes and libraries, with the assumption that you already know how to program in another language. For a briefer, less complete introduction to the language, see the language samples page.

To learn more about Dart’s core libraries, see the library tour. Whenever you want more details about a language feature, consult the Dart language specification.

Note: You can play with most of Dart’s language features using DartPad (learn more). Open DartPad.

This page uses embedded DartPads to display some of the examples. If you see empty boxes instead of DartPads, go to the DartPad troubleshooting page.

A basic Dart program

The following code uses many of Dart’s most basic features:

// Define a function. void printInteger(int aNumber) { print('The number is $aNumber.'); // Print to console. } // This is where the app starts executing. void main() { var number = 42; // Declare and initialize a variable. printInteger(number); // Call a function. }

Here’s what this program uses that applies to all (or almost all) Dart apps:

A single-line comment. Dart also supports multi-line and document comments. For details, see Comments.
A special type that indicates a value that’s never used. Functions like and that don’t explicitly return a value have the return type.
Another type, indicating an integer. Some additional built-in types are , , and .
A number literal. Number literals are a kind of compile-time constant.
A handy way to display output.
(or )
A string literal.
(or )
String interpolation: including a variable or expression’s string equivalent inside of a string literal. For more information, see Strings.
The special, required, top-level function where app execution starts. For more information, see The main() function.
A way to declare a variable without specifying its type. The type of this variable () is determined by its initial value ().

Note: This site’s code follows the conventions in the Dart style guide.

Important concepts

As you learn about the Dart language, keep these facts and concepts in mind:

  • Everything you can place in a variable is an object, and every object is an instance of a class. Even numbers, functions, and are objects. With the exception of (if you enable sound null safety), all objects inherit from the class.

    Version note:Null safety was introduced in Dart 2.12. Using null safety requires a language version of at least 2.12.

  • Although Dart is strongly typed, type annotations are optional because Dart can infer types. In the code above, is inferred to be of type .

  • If you enable null safety, variables can’t contain unless you say they can. You can make a variable nullable by putting a question mark () at the end of its type. For example, a variable of type might be an integer, or it might be . If you know that an expression never evaluates to but Dart disagrees, you can add to assert that it isn’t null (and to throw an exception if it is). An example:

  • When you want to explicitly say that any type is allowed, use the type (if you’ve enabled null safety), , or — if you must defer type checking until runtime — the special type .

  • Dart supports generic types, like (a list of integers) or (a list of objects of any type).

  • Dart supports top-level functions (such as ), as well as functions tied to a class or object (static and instance methods, respectively). You can also create functions within functions (nested or local functions).

  • Similarly, Dart supports top-level variables, as well as variables tied to a class or object (static and instance variables). Instance variables are sometimes known as fields or properties.

  • Unlike Java, Dart doesn’t have the keywords , , and . If an identifier starts with an underscore (), it’s private to its library. For details, see Libraries and visibility.

  • Identifiers can start with a letter or underscore (), followed by any combination of those characters plus digits.

  • Dart has both expressions (which have runtime values) and statements (which don’t). For example, the conditional expression has a value of or . Compare that to an if-else statement, which has no value. A statement often contains one or more expressions, but an expression can’t directly contain a statement.

  • Dart tools can report two kinds of problems: warnings and errors. Warnings are just indications that your code might not work, but they don’t prevent your program from executing. Errors can be either compile-time or run-time. A compile-time error prevents the code from executing at all; a run-time error results in an exception being raised while the code executes.


The following table lists the words that the Dart language treats specially.

Avoid using these words as identifiers. However, if necessary, the keywords marked with superscripts can be identifiers:

  • Words with the superscript 1 are contextual keywords, which have meaning only in specific places. They’re valid identifiers everywhere.

  • Words with the superscript 2 are built-in identifiers. To simplify the task of porting JavaScript code to Dart, these keywords are valid identifiers in most places, but they can’t be used as class or type names, or as import prefixes.

  • Words with the superscript 3 are limited reserved words related to asynchrony support. You can’t use or as an identifier in any function body marked with , , or .

All other words in the table are reserved words, which can’t be identifiers.


Here’s an example of creating a variable and initializing it:

Variables store references. The variable called contains a reference to a object with a value of “Bob”.

The type of the variable is inferred to be , but you can change that type by specifying it. If an object isn’t restricted to a single type, specify the type (or if necessary).

Another option is to explicitly declare the type that would be inferred:

Note: This page follows the style guide recommendation of using , rather than type annotations, for local variables.

Default value

Uninitialized variables that have a nullable type have an initial value of . (If you haven’t opted into null safety, then every variable has a nullable type.) Even variables with numeric types are initially null, because numbers—like everything else in Dart—are objects.

int? lineCount; assert(lineCount == null);

Note: Production code ignores the call. During development, on the other hand, throws an exception if condition is false. For details, see Assert.

If you enable null safety, then you must initialize the values of non-nullable variables before you use them:

You don’t have to initialize a local variable where it’s declared, but you do need to assign it a value before it’s used. For example, the following code is valid because Dart can detect that is non-null by the time it’s passed to :

int lineCount; if (weLikeToCount) { lineCount = countLines(); } else { lineCount = 0; } print(lineCount);

Top-level and class variables are lazily initialized; the initialization code runs the first time the variable is used.

Late variables

Dart 2.12 added the modifier, which has two use cases:

  • Declaring a non-nullable variable that’s initialized after its declaration.
  • Lazily initializing a variable.

Often Dart’s control flow analysis can detect when a non-nullable variable is set to a non-null value before it’s used, but sometimes analysis fails. Two common cases are top-level variables and instance variables: Dart often can’t determine whether they’re set, so it doesn’t try.

If you’re sure that a variable is set before it’s used, but Dart disagrees, you can fix the error by marking the variable as :

late String description; void main() { description = 'Feijoada!'; print(description); }

If you fail to initialize a variable, a runtime error occurs when the variable is used.

When you mark a variable as but initialize it at its declaration, then the initializer runs the first time the variable is used. This lazy initialization is handy in a couple of cases:

  • The variable might not be needed, and initializing it is costly.
  • You’re initializing an instance variable, and its initializer needs access to .

In the following example, if the variable is never used, then the expensive function is never called:

// This is the program's only call to _readThermometer(). late String temperature = _readThermometer(); // Lazily initialized.

Final and const

If you never intend to change a variable, use or , either instead of or in addition to a type. A final variable can be set only once; a const variable is a compile-time constant. (Const variables are implicitly final.)

Note:Instance variables can be but not .

Here’s an example of creating and setting a variable:

final name = 'Bob'; // Without a type annotation final String nickname = 'Bobby';

You can’t change the value of a variable:

name = 'Alice'; // Error: a final variable can only be set once.

Use for variables that you want to be compile-time constants. If the const variable is at the class level, mark it . Where you declare the variable, set the value to a compile-time constant such as a number or string literal, a const variable, or the result of an arithmetic operation on constant numbers:

const bar = 1000000; // Unit of pressure (dynes/cm2) const double atm = 1.01325 * bar; // Standard atmosphere

The keyword isn’t just for declaring constant variables. You can also use it to create constant values, as well as to declare constructors that create constant values. Any variable can have a constant value.

var foo = const []; final bar = const []; const baz = []; // Equivalent to `const []`

You can omit from the initializing expression of a declaration, like for above. For details, see DON’T use const redundantly.

You can change the value of a non-final, non-const variable, even if it used to have a value:

foo = [1, 2, 3]; // Was const []

You can’t change the value of a variable:

baz = [42]; // Error: Constant variables can't be assigned a value.

You can define constants that use type checks and casts ( and ), collection , and spread operators ( and ):

const Object i = 3; // Where i is a const Object with an int value... const list = [i as int]; // Use a typecast. const map = {if (i is int) i: 'int'}; // Use is and collection if. const set = {if (list is List<int>) ...list}; // ...and a spread.

Note: Although a object cannot be modified, its fields can be changed. In comparison, a object and its fields cannot be changed: they’re immutable.

For more information on using to create constant values, see Lists, Maps, and Classes.

Built-in types

The Dart language has special support for the following:

This support includes the ability to create objects using literals. For example, is a string literal, and is a boolean literal.

Because every variable in Dart refers to an object—an instance of a class—you can usually use constructors to initialize variables. Some of the built-in types have their own constructors. For example, you can use the constructor to create a map.

Some other types also have special roles in the Dart language:

  • : The superclass of all Dart classes except .
  • and : Used in asynchrony support.
  • : Used in for-in loops and in synchronous generator functions.
  • : Indicates that an expression can never successfully finish evaluating. Most often used for functions that always throw an exception.
  • : Indicates that you want to disable static checking. Usually you should use or instead.
  • : Indicates that a value is never used. Often used as a return type.

The , , , and classes have special roles in the class hierarchy, as described in the top-and-bottom section of Understanding null safety.


Dart numbers come in two flavors:

Integer values no larger than 64 bits, depending on the platform. On native platforms, values can be from -263 to 263 - 1. On the web, integer values are represented as JavaScript numbers (64-bit floating-point values with no fractional part) and can be from -253 to 253 - 1.

64-bit (double-precision) floating-point numbers, as specified by the IEEE 754 standard.

Both and are subtypes of . The num type includes basic operators such as +, -, /, and *, and is also where you’ll find ,, and , among other methods. (Bitwise operators, such as >>, are defined in the class.) If num and its subtypes don’t have what you’re looking for, the dart:math library might.

Integers are numbers without a decimal point. Here are some examples of defining integer literals:

var x = 1; var hex = 0xDEADBEEF; var exponent = 8e5;

If a number includes a decimal, it is a double. Here are some examples of defining double literals:

var y = 1.1; var exponents = 1.42e5;

You can also declare a variable as a num. If you do this, the variable can have both integer and double values.

num x = 1; // x can have both int and double values x += 2.5;

Integer literals are automatically converted to doubles when necessary:

double z = 1; // Equivalent to double z = 1.0.

Here’s how you turn a string into a number, or vice versa:

// String -> int var one = int.parse('1'); assert(one == 1); // String -> double var onePointOne = double.parse('1.1'); assert(onePointOne == 1.1); // int -> String String oneAsString = 1.toString(); assert(oneAsString == '1'); // double -> String String piAsString = 3.14159.toStringAsFixed(2); assert(piAsString == '3.14');

The type specifies the traditional bitwise shift (, , ), complement (), AND (), OR (), and XOR () operators, which are useful for manipulating and masking flags in bit fields. For example:

assert((3 << 1) == 6); // 0011 << 1 == 0110 assert((3 | 4) == 7); // 0011 | 0100 == 0111 assert((3 & 4) == 0); // 0011 & 0100 == 0000

For more examples, see the bitwise and shift operator section.

Literal numbers are compile-time constants. Many arithmetic expressions are also compile-time constants, as long as their operands are compile-time constants that evaluate to numbers.

const msPerSecond = 1000; const secondsUntilRetry = 5; const msUntilRetry = secondsUntilRetry * msPerSecond;

For more information, see Numbers in Dart.


A Dart string ( object) holds a sequence of UTF-16 code units. You can use either single or double quotes to create a string:

var s1 = 'Single quotes work well for string literals.'; var s2 = "Double quotes work just as well."; var s3 = 'It\'s easy to escape the string delimiter.'; var s4 = "It's even easier to use the other delimiter.";

You can put the value of an expression inside a string by using . If the expression is an identifier, you can skip the {}. To get the string corresponding to an object, Dart calls the object’s method.

var s = 'string interpolation'; assert('Dart has $s, which is very handy.' == 'Dart has string interpolation, ' 'which is very handy.'); assert('That deserves all caps. ' '${s.toUpperCase()} is very handy!' == 'That deserves all caps. ' 'STRING INTERPOLATION is very handy!');

Note: The operator tests whether two objects are equivalent. Two strings are equivalent if they contain the same sequence of code units.

You can concatenate strings using adjacent string literals or the operator:

var s1 = 'String ' 'concatenation' " works even over line breaks."; assert(s1 == 'String concatenation works even over ' 'line breaks.'); var s2 = 'The + operator ' + 'works, as well.'; assert(s2 == 'The + operator works, as well.');

Another way to create a multi-line string: use a triple quote with either single or double quotation marks:

var s1 = ''' You can create multi-line strings like this one. '''; var s2 = """This is also a multi-line string.""";

You can create a “raw” string by prefixing it with :

var s = r'In a raw string, not even \n gets special treatment.';

See Runes and grapheme clusters for details on how to express Unicode characters in a string.

Literal strings are compile-time constants, as long as any interpolated expression is a compile-time constant that evaluates to null or a numeric, string, or boolean value.

// These work in a const string. const aConstNum = 0; const aConstBool = true; const aConstString = 'a constant string'; // These do NOT work in a const string. var aNum = 0; var aBool = true; var aString = 'a string'; const aConstList = [1, 2, 3]; const validConstString = '$aConstNum $aConstBool $aConstString'; // const invalidConstString = '$aNum $aBool $aString $aConstList';

For more information on using strings, see Strings and regular expressions.


To represent boolean values, Dart has a type named . Only two objects have type bool: the boolean literals and , which are both compile-time constants.

Dart’s type safety means that you can’t use code like or . Instead, explicitly check for values, like this:

// Check for an empty string. var fullName = ''; assert(fullName.isEmpty); // Check for zero. var hitPoints = 0; assert(hitPoints <= 0); // Check for null. var unicorn; assert(unicorn == null); // Check for NaN. var iMeantToDoThis = 0 / 0; assert(iMeantToDoThis.isNaN);


Perhaps the most common collection in nearly every programming language is the array, or ordered group of objects. In Dart, arrays are objects, so most people just call them lists.

Dart list literals look like JavaScript array literals. Here’s a simple Dart list:

Note: Dart infers that has type . If you try to add non-integer objects to this list, the analyzer or runtime raises an error. For more information, read about type inference.

You can add a comma after the last item in a Dart collection literal. This trailing comma doesn’t affect the collection, but it can help prevent copy-paste errors.

var list = [ 'Car', 'Boat', 'Plane', ];

Lists use zero-based indexing, where 0 is the index of the first value and is the index of the last value. You can get a list’s length and refer to list values just as you would in JavaScript:

var list = [1, 2, 3]; assert(list.length == 3); assert(list[1] == 2); list[1] = 1; assert(list[1] == 1);

To create a list that’s a compile-time constant, add before the list literal:

var constantList = const [1, 2, 3]; // constantList[1] = 1; // This line will cause an error.

Dart 2.3 introduced the spread operator () and the null-aware spread operator (), which provide a concise way to insert multiple values into a collection.

For example, you can use the spread operator () to insert all the values of a list into another list:

var list = [1, 2, 3]; var list2 = [0, ...list]; assert(list2.length == 4);

If the expression to the right of the spread operator might be null, you can avoid exceptions by using a null-aware spread operator ():

var list; var list2 = [0, ...?list]; assert(list2.length == 1);

For more details and examples of using the spread operator, see the spread operator proposal.

Dart also offers collection if and collection for, which you can use to build collections using conditionals () and repetition ().

Here’s an example of using collection if to create a list with three or four items in it:

var nav = [ 'Home', 'Furniture', 'Plants', if (promoActive) 'Outlet' ];

Here’s an example of using collection for to manipulate the items of a list before adding them to another list:

var listOfInts = [1, 2, 3]; var listOfStrings = [ '#0', for (var i in listOfInts) '#$i' ]; assert(listOfStrings[1] == '#1');

For more details and examples of using collection and , see the control flow collections proposal.

The List type has many handy methods for manipulating lists. For more information about lists, see Generics and Collections.


A set in Dart is an unordered collection of unique items. Dart support for sets is provided by set literals and the type.

Here is a simple Dart set, created using a set literal:

var halogens = {'fluorine', 'chlorine', 'bromine', 'iodine', 'astatine'};

Note: Dart infers that has the type . If you try to add the wrong type of value to the set, the analyzer or runtime raises an error. For more information, read about type inference.

To create an empty set, use preceded by a type argument, or assign to a variable of type :

var names = <String>{}; // Set<String> names = {}; // This works, too. // var names = {}; // Creates a map, not a set.

Set or map? The syntax for map literals is similar to that for set literals. Because map literals came first, defaults to the type. If you forget the type annotation on or the variable it’s assigned to, then Dart creates an object of type .

Add items to an existing set using the or methods:

var elements = <String>{}; elements.add('fluorine'); elements.addAll(halogens);

Use to get the number of items in the set:

var elements = <String>{}; elements.add('fluorine'); elements.addAll(halogens); assert(elements.length == 5);

To create a set that’s a compile-time constant, add before the set literal:

final constantSet = const { 'fluorine', 'chlorine', 'bromine', 'iodine', 'astatine', }; // constantSet.add('helium'); // This line will cause an error.

Sets support spread operators ( and ) and collection and , just like lists do. For more information, see the list spread operator and list collection operator discussions.

For more information about sets, see Generics and Sets.


In general, a map is an object that associates keys and values. Both keys and values can be any type of object. Each key occurs only once, but you can use the same value multiple times. Dart support for maps is provided by map literals and the type.

Here are a couple of simple Dart maps, created using map literals:

var gifts = { // Key: Value 'first': 'partridge', 'second': 'turtledoves', 'fifth': 'golden rings' }; var nobleGases = { 2: 'helium', 10: 'neon', 18: 'argon', };

Note: Dart infers that has the type and has the type . If you try to add the wrong type of value to either map, the analyzer or runtime raises an error. For more information, read about type inference.

You can create the same objects using a Map constructor:

var gifts = Map<String, String>(); gifts['first'] = 'partridge'; gifts['second'] = 'turtledoves'; gifts['fifth'] = 'golden rings'; var nobleGases = Map<int, String>(); nobleGases[2] = 'helium'; nobleGases[10] = 'neon'; nobleGases[18] = 'argon';

Note: If you come from a language like C# or Java, you might expect to see instead of just . In Dart, the keyword is optional. For details, see Using constructors.

Add a new key-value pair to an existing map just as you would in JavaScript:

var gifts = {'first': 'partridge'}; gifts['fourth'] = 'calling birds'; // Add a key-value pair

Retrieve a value from a map the same way you would in JavaScript:

var gifts = {'first': 'partridge'}; assert(gifts['first'] == 'partridge');

If you look for a key that isn’t in a map, you get a null in return:

var gifts = {'first': 'partridge'}; assert(gifts['fifth'] == null);

Use to get the number of key-value pairs in the map:

var gifts = {'first': 'partridge'}; gifts['fourth'] = 'calling birds'; assert(gifts.length == 2);

To create a map that’s a compile-time constant, add before the map literal:

final constantMap = const { 2: 'helium', 10: 'neon', 18: 'argon', }; // constantMap[2] = 'Helium'; // This line will cause an error.

Maps support spread operators ( and ) and collection and , just like lists do. For details and examples, see the spread operator proposal and the control flow collections proposal.

For more information about maps, see the generics section and the library tour’s coverage of the API.

Runes and grapheme clusters

In Dart, runes expose the Unicode code points of a string. You can use the characters package to view or manipulate user-perceived characters, also known as Unicode (extended) grapheme clusters.

Unicode defines a unique numeric value for each letter, digit, and symbol used in all of the world’s writing systems. Because a Dart string is a sequence of UTF-16 code units, expressing Unicode code points within a string requires special syntax. The usual way to express a Unicode code point is , where XXXX is a 4-digit hexadecimal value. For example, the heart character (♥) is . To specify more or less than 4 hex digits, place the value in curly brackets. For example, the laughing emoji (😆) is .

If you need to read or write individual Unicode characters, use the getter defined on String by the characters package. The returned object is the string as a sequence of grapheme clusters. Here’s an example of using the characters API:

The output, depending on your environment, looks something like this:

For details on using the characters package to manipulate strings, see the example and API reference for the characters package.


A object represents an operator or identifier declared in a Dart program. You might never need to use symbols, but they’re invaluable for APIs that refer to identifiers by name, because minification changes identifier names but not identifier symbols.

To get the symbol for an identifier, use a symbol literal, which is just followed by the identifier:

Symbol literals are compile-time constants.


Dart is a true object-oriented language, so even functions are objects and have a type, Function. This means that functions can be assigned to variables or passed as arguments to other functions. You can also call an instance of a Dart class as if it were a function. For details, see Callable classes.

Here’s an example of implementing a function:

bool isNoble(int atomicNumber) { return _nobleGases[atomicNumber] != null; }

Although Effective Dart recommends type annotations for public APIs, the function still works if you omit the types:

isNoble(atomicNumber) { return _nobleGases[atomicNumber] != null; }

For functions that contain just one expression, you can use a shorthand syntax:

bool isNoble(int atomicNumber) => _nobleGases[atomicNumber] != null;

The syntax is a shorthand for . The notation is sometimes referred to as arrow syntax.

Note: Only an expression—not a statement—can appear between the arrow (=>) and the semicolon (;). For example, you can’t put an if statement there, but you can use a conditional expression.


A function can have any number of required positional parameters. These can be followed either by named parameters or by optional positional parameters (but not both).

Note: Some APIs — notably Flutter widget constructors — use only named parameters, even for parameters that are mandatory. See the next section for details.

You can use trailing commas when you pass arguments to a function or when you define function parameters.

Named parameters

Named parameters are optional unless they’re specifically marked as .

When calling a function, you can specify named parameters using . For example:

enableFlags(bold: true, hidden: false);

When defining a function, use to specify named parameters:

/// Sets the [bold] and [hidden] flags ... void enableFlags({bool? bold, bool? hidden}) {...}

Tip: If a parameter is optional but can’t be , provide a default value.

Although named parameters are a kind of optional parameter, you can annotate them with to indicate that the parameter is mandatory — that users must provide a value for the parameter. For example:

If someone tries to create a without specifying the argument, then the analyzer reports an issue.

Optional positional parameters

Wrapping a set of function parameters in marks them as optional positional parameters:

String say(String from, String msg, [String? device]) { var result = '$from says $msg'; if (device != null) { result = '$result with a $device'; } return result; }

Here’s an example of calling this function without the optional parameter:

assert(say('Bob', 'Howdy') == 'Bob says Howdy');

And here’s an example of calling this function with the third parameter:

assert(say('Bob', 'Howdy', 'smoke signal') == 'Bob says Howdy with a smoke signal');

Default parameter values

Your function can use to define default values for both named and positional parameters. The default values must be compile-time constants. If no default value is provided, the default value is .

Here’s an example of setting default values for named parameters:

/// Sets the [bold] and [hidden] flags ... void enableFlags({bool bold = false, bool hidden = false}) {...} // bold will be true; hidden will be false. enableFlags(bold: true);

Deprecation note: Old code might use a colon () instead of to set default values of named parameters. The reason is that originally, only was supported for named parameters. That support might be deprecated, so we recommend that you use to specify default values.

The next example shows how to set default values for positional parameters:

String say(String from, String msg, [String device = 'carrier pigeon']) { var result = '$from says $msg with a $device'; return result; } assert(say('Bob', 'Howdy') == 'Bob says Howdy with a carrier pigeon');

You can also pass lists or maps as default values. The following example defines a function, , that specifies a default list for the parameter and a default map for the parameter.

void doStuff( {List<int> list = const [1, 2, 3], Map<String, String> gifts = const { 'first': 'paper', 'second': 'cotton', 'third': 'leather' }}) { print('list: $list'); print('gifts: $gifts'); }

The main() function

Every app must have a top-level function, which serves as the entrypoint to the app. The function returns and has an optional parameter for arguments.

Here’s a simple function:

void main() { print('Hello, World!'); }

Here’s an example of the function for a command-line app that takes arguments:

// Run the app like this: dart args.dart 1 test void main(List<String> arguments) { print(arguments); assert(arguments.length == 2); assert(int.parse(arguments[0]) == 1); assert(arguments[1] == 'test'); }

You can use the args library to define and parse command-line arguments.

Functions as first-class objects

You can pass a function as a parameter to another function. For example:

void printElement(int element) { print(element); } var list = [1, 2, 3]; // Pass printElement as a parameter. list.forEach(printElement);

You can also assign a function to a variable, such as:

var loudify = (msg) => '!!! ${msg.toUpperCase()} !!!'; assert(loudify('hello') == '!!! HELLO !!!');

This example uses an anonymous function. More about those in the next section.

Anonymous functions

Most functions are named, such as or . You can also create a nameless function called an anonymous function, or sometimes a lambda or closure. You might assign an anonymous function to a variable so that, for example, you can add or remove it from a collection.

An anonymous function looks similar to a named function— zero or more parameters, separated by commas and optional type annotations, between parentheses.

The code block that follows contains the function’s body:

The following example defines an anonymous function with an untyped parameter, . The function, invoked for each item in the list, prints a string that includes the value at the specified index.

const list = ['apples', 'bananas', 'oranges']; list.forEach((item) { print('${list.indexOf(item)}: $item'); });

Click Run to execute the code.

If the function contains only a single expression or return statement, you can shorten it using arrow notation. Paste the following line into DartPad and click Run to verify that it is functionally equivalent.

list.forEach( (item) => print('${list.indexOf(item)}: $item'));

Lexical scope

Dart is a lexically scoped language, which means that the scope of variables is determined statically, simply by the layout of the code. You can “follow the curly braces outwards” to see if a variable is in scope.

Here is an example of nested functions with variables at each scope level:

bool topLevel = true; void main() { var insideMain = true; void myFunction() { var insideFunction = true; void nestedFunction() { var insideNestedFunction = true; assert(topLevel); assert(insideMain); assert(insideFunction); assert(insideNestedFunction); } } }

Notice how can use variables from every level, all the way up to the top level.

Lexical closures

A closure is a function object that has access to variables in its lexical scope, even when the function is used outside of its original scope.

Functions can close over variables defined in surrounding scopes. In the following example, captures the variable . Wherever the returned function goes, it remembers .

/// Returns a function that adds [addBy] to the /// function's argument. Function makeAdder(int addBy) { return (int i) => addBy + i; } void main() { // Create a function that adds 2. var add2 = makeAdder(2); // Create a function that adds 4. var add4 = makeAdder(4); assert(add2(3) == 5); assert(add4(3) == 7); }

Testing functions for equality

Here’s an example of testing top-level functions, static methods, and instance methods for equality:

void foo() {} // A top-level function class A { static void bar() {} // A static method void baz() {} // An instance method } void main() { Function x; // Comparing top-level functions. x = foo; assert(foo == x); // Comparing static methods. x =; assert( == x); // Comparing instance methods. var v = A(); // Instance #1 of A var w = A(); // Instance #2 of A var y = w; x = w.baz; // These closures refer to the same instance (#2), // so they're equal. assert(y.baz == x); // These closures refer to different instances, // so they're unequal. assert(v.baz != w.baz); }

Return values

All functions return a value. If no return value is specified, the statement is implicitly appended to the function body.

foo() {} assert(foo() == null);


Dart supports the operators shown in the following table. You can implement many of these operators as class members.

unary postfix
unary prefix
bitwise AND
bitwise XOR
bitwise OR
relational and type test
logical AND
logical OR
if null

Warning: Operator precedence is an approximation of the behavior of a Dart parser. For definitive answers, consult the grammar in the Dart language specification.

When you use operators, you create expressions. Here are some examples of operator expressions:

a++ a + b a = b a == b c ? a : b a is T

In the operator table, each operator has higher precedence than the operators in the rows that follow it. For example, the multiplicative operator has higher precedence than (and thus executes before) the equality operator , which has higher precedence than the logical AND operator . That precedence means that the following two lines of code execute the same way:

// Parentheses improve readability. if ((n % i == 0) && (d % i == 0)) ... // Harder to read, but equivalent. if (n % i == 0 && d % i == 0) ...

Warning: For operators that take two operands, the leftmost operand determines which method is used. For example, if you have a object and a object, then uses addition ().

Arithmetic operators

Dart supports the usual arithmetic operators, as shown in the following table.

Unary minus, also known as negation (reverse the sign of the expression)
Divide, returning an integer result
Get the remainder of an integer division (modulo)


assert(2 + 3 == 5); assert(2 - 3 == -1); assert(2 * 3 == 6); assert(5 / 2 == 2.5); // Result is a double assert(5 ~/ 2 == 2); // Result is an int assert(5 % 2 == 1); // Remainder assert('5/2 = ${5 ~/ 2} r ${5 % 2}' == '5/2 = 2 r 1');

Dart also supports both prefix and postfix increment and decrement operators.

(expression value is )
(expression value is )
(expression value is )
(expression value is )


int a; int b; a = 0; b = ++a; // Increment a before b gets its value. assert(a == b); // 1 == 1 a = 0; b = a++; // Increment a AFTER b gets its value. assert(a != b); // 1 != 0 a = 0; b = --a; // Decrement a before b gets its value. assert(a == b); // -1 == -1 a = 0; b = a--; // Decrement a AFTER b gets its value. assert(a != b); // -1 != 0

Equality and relational operators

The following table lists the meanings of equality and relational operators.

Equal; see discussion below
Not equal
Greater than
Less than
Greater than or equal to
Less than or equal to

To test whether two objects x and y represent the same thing, use the operator. (In the rare case where you need to know whether two objects are the exact same object, use the identical() function instead.) Here’s how the operator works:

  1. If x or y is null, return true if both are null, and false if only one is null.

  2. Return the result of invoking the method on x with the argument y. (That’s right, operators such as are methods that are invoked on their first operand. For details, see Operators.)

Here’s an example of using each of the equality and relational operators:

assert(2 == 2); assert(2 != 3); assert(3 > 2); assert(2 < 3); assert(3 >= 3); assert(2 <= 3);

Type test operators

The , , and operators are handy for checking types at runtime.

Typecast (also used to specify library prefixes)
True if the object has the specified type
True if the object doesn’t have the specified type

The result of is true if implements the interface specified by . For example, is always true.

Use the operator to cast an object to a particular type if and only if you are sure that the object is of that type. Example:

(employee as Person).firstName = 'Bob';

If you aren’t sure that the object is of type , then use to check the type before using the object.

if (employee is Person) { // Type check employee.firstName = 'Bob'; }

Note: The code isn’t equivalent. If is null or not a , the first example throws an exception; the second does nothing.

Assignment operators

As you’ve already seen, you can assign values using the operator. To assign only if the assigned-to variable is null, use the operator.

// Assign value to a a = value; // Assign value to b if b is null; otherwise, b stays the same b ??= value;

Compound assignment operators such as combine an operation with an assignment.

Here’s how compound assignment operators work:

Compound assignmentEquivalent expression
For an operator op:

The following example uses assignment and compound assignment operators:

var a = 2; // Assign using = a *= 3; // Assign and multiply: a = a * 3 assert(a == 6);

Logical operators

You can invert or combine boolean expressions using the logical operators.

inverts the following expression (changes false to true, and vice versa)
logical OR
logical AND

Here’s an example of using the logical operators:

if (!done && (col == 0 || col == 3)) { // ...Do something... }

Bitwise and shift operators

You can manipulate the individual bits of numbers in Dart. Usually, you’d use these bitwise and shift operators with integers.

Unary bitwise complement (0s become 1s; 1s become 0s)
Shift left
Shift right
Unsigned shift right

Here’s an example of using bitwise and shift operators:

final value = 0x22; final bitmask = 0x0f; assert((value & bitmask) == 0x02); // AND assert((value & ~bitmask) == 0x20); // AND NOT assert((value | bitmask) == 0x2f); // OR assert((value ^ bitmask) == 0x2d); // XOR assert((value << 4) == 0x220); // Shift left assert((value >> 4) == 0x02); // Shift right assert((value >>> 4) == 0x02); // Unsigned shift right assert((-value >> 4) == -0x03); // Shift right assert((-value >>> 4) > 0); // Unsigned shift right

Version note: The operator (known as triple-shift or unsigned shift) requires a language version of at least 2.14.

Conditional expressions

Dart has two operators that let you concisely evaluate expressions that might otherwise require if-else statements:

If condition is true, evaluates expr1 (and returns its value); otherwise, evaluates and returns the value of expr2.
If expr1 is non-null, returns its value; otherwise, evaluates and returns the value of expr2.

When you need to assign a value based on a boolean expression, consider using and .

var visibility = isPublic ? 'public' : 'private';

If the boolean expression tests for null, consider using .

String playerName(String? name) => name ?? 'Guest';

The previous example could have been written at least two other ways, but not as succinctly:

// Slightly longer version uses ?: operator. String playerName(String? name) => name != null ? name : 'Guest'; // Very long version uses if-else statement. String playerName(String? name) { if (name != null) { return name; } else { return 'Guest'; } }

Cascade notation

Cascades (, ) allow you to make a sequence of operations on the same object. In addition to function calls, you can also access fields on that same object. This often saves you the step of creating a temporary variable and allows you to write more fluid code.

Consider the following code:

var paint = Paint() ..color = ..strokeCap = StrokeCap.round ..strokeWidth = 5.0;

The constructor, , returns a object. The code that follows the cascade notation operates on this object, ignoring any values that might be returned.

The previous example is equivalent to this code:

var paint = Paint(); paint.color =; paint.strokeCap = StrokeCap.round; paint.strokeWidth = 5.0;

If the object that the cascade operates on can be null, then use a null-shorting cascade () for the first operation. Starting with guarantees that none of the cascade operations are attempted on that null object.

querySelector('#confirm') // Get an object. ?..text = 'Confirm' // Use its members. ..classes.add('important') ..onClick.listen((e) => window.alert('Confirmed!'));

Version note: The syntax requires a language version of at least 2.12.

The previous code is equivalent to the following:

var button = querySelector('#confirm'); button?.text = 'Confirm'; button?.classes.add('important'); button?.onClick.listen((e) => window.alert('Confirmed!'));

You can also nest cascades. For example:

final addressBook = (AddressBookBuilder() = 'jenny' = '[email protected]' = (PhoneNumberBuilder() ..number = '415-555-0100' ..label = 'home') .build()) .build();

Be careful to construct your cascade on a function that returns an actual object. For example, the following code fails:

var sb = StringBuffer(); sb.write('foo') ..write('bar'); // Error: method 'write' isn't defined for 'void'.

The call returns void, and you can’t construct a cascade on .

Note: Strictly speaking, the “double dot” notation for cascades isn’t an operator. It’s just part of the Dart syntax.

Other operators

You’ve seen most of the remaining operators in other examples:

Function applicationRepresents a function call
List accessRefers to the value at the specified index in the list
Member accessRefers to a property of an expression; example: selects property from expression
Conditional member accessLike , but the leftmost operand can be null; example: selects property from expression unless is null (in which case the value of is null)

For more information about the , , and operators, see Classes.

Control flow statements

You can control the flow of your Dart code using any of the following:

  • and
  • loops
  • and - loops
  • and
  • and

You can also affect the control flow using and , as explained in Exceptions.

If and else

Dart supports statements with optional statements, as the next sample shows. Also see conditional expressions.

if (isRaining()) { you.bringRainCoat(); } else if (isSnowing()) { you.wearJacket(); } else { car.putTopDown(); }

Unlike JavaScript, conditions must use boolean values, nothing else. See Booleans for more information.

For loops

You can iterate with the standard loop. For example:

var message = StringBuffer('Dart is fun'); for (var i = 0; i < 5; i++) { message.write('!'); }

Closures inside of Dart’s loops capture the value of the index, avoiding a common pitfall found in JavaScript. For example, consider:

var callbacks = []; for (var i = 0; i < 2; i++) { callbacks.add(() => print(i)); } callbacks.forEach((c) => c());

The output is and then , as expected. In contrast, the example would print and then in JavaScript.

If the object that you are iterating over is an Iterable (such as List or Set) and if you don’t need to know the current iteration counter, you can use the form of iteration:

for (final candidate in candidates) { candidate.interview(); }

Tip: To practice using , follow the Iterable collections codelab.

Iterable classes also have a forEach() method as another option:

var collection = [1, 2, 3]; collection.forEach(print); // 1 2 3

While and do-while

A loop evaluates the condition before the loop:

while (!isDone()) { doSomething(); }

A - loop evaluates the condition after the loop:

do { printLine(); } while (!atEndOfPage());

Break and continue

Use to stop looping:

while (true) { if (shutDownRequested()) break; processIncomingRequests(); }

Use to skip to the next loop iteration:

for (int i = 0; i < candidates.length; i++) { var candidate = candidates[i]; if (candidate.yearsExperience < 5) { continue; } candidate.interview(); }

You might write that example differently if you’re using an such as a list or set:

candidates .where((c) => c.yearsExperience >= 5) .forEach((c) => c.interview());

Switch and case

Switch statements in Dart compare integer, string, or compile-time constants using . The compared objects must all be instances of the same class (and not of any of its subtypes), and the class must not override . Enumerated types work well in statements.

Each non-empty clause ends with a statement, as a rule. Other valid ways to end a non-empty clause are a , , or statement.

Use a clause to execute code when no clause matches:

var command = 'OPEN'; switch (command) { case 'CLOSED': executeClosed(); break; case 'PENDING': executePending(); break; case 'APPROVED': executeApproved(); break; case 'DENIED': executeDenied(); break; case 'OPEN': executeOpen(); break; default: executeUnknown(); }

The following example omits the statement in a clause, thus generating an error:

var command = 'OPEN'; switch (command) { case 'OPEN': executeOpen(); // ERROR: Missing break case 'CLOSED': executeClosed(); break; }

However, Dart does support empty clauses, allowing a form of fall-through:

var command = 'CLOSED'; switch (command) { case 'CLOSED': // Empty case falls through. case 'NOW_CLOSED': // Runs for both CLOSED and NOW_CLOSED. executeNowClosed(); break; }

If you really want fall-through, you can use a statement and a label:

var command = 'CLOSED'; switch (command) { case 'CLOSED': executeClosed(); continue nowClosed; // Continues executing at the nowClosed label. nowClosed: case 'NOW_CLOSED': // Runs for both CLOSED and NOW_CLOSED. executeNowClosed(); break; }

A clause can have local variables, which are visible only inside the scope of that clause.


During development, use an assert statement — ; — to disrupt normal execution if a boolean condition is false. You can find examples of assert statements throughout this tour. Here are some more:

// Make sure the variable has a non-null value. assert(text != null); // Make sure the value is less than 100. assert(number < 100); // Make sure this is an https URL. assert(urlString.startsWith('https'));

To attach a message to an assertion, add a string as the second argument to (optionally with a trailing comma):

assert(urlString.startsWith('https'), 'URL ($urlString) should start with "https".');

The first argument to can be any expression that resolves to a boolean value. If the expression’s value is true, the assertion succeeds and execution continues. If it’s false, the assertion fails and an exception (an ) is thrown.

When exactly do assertions work? That depends on the tools and framework you’re using:

  • Flutter enables assertions in debug mode.
  • Development-only tools such as dartdevc typically enable assertions by default.
  • Some tools, such as and support assertions through a command-line flag: .

In production code, assertions are ignored, and the arguments to aren’t evaluated.


Your Dart code can throw and catch exceptions. Exceptions are errors indicating that something unexpected happened. If the exception isn’t caught, the isolate that raised the exception is suspended, and typically the isolate and its program are terminated.

In contrast to Java, all of Dart’s exceptions are unchecked exceptions. Methods don’t declare which exceptions they might throw, and you aren’t required to catch any exceptions.

Dart provides and types, as well as numerous predefined subtypes. You can, of course, define your own exceptions. However, Dart programs can throw any non-null object—not just Exception and Error objects—as an exception.


Here’s an example of throwing, or raising, an exception:

throw FormatException('Expected at least 1 section');

You can also throw arbitrary objects:

Note: Production-quality code usually throws types that implement or .

Because throwing an exception is an expression, you can throw exceptions in => statements, as well as anywhere else that allows expressions:

void distanceTo(Point other) => throw UnimplementedError();


Catching, or capturing, an exception stops the exception from propagating (unless you rethrow the exception). Catching an exception gives you a chance to handle it:

try { breedMoreLlamas(); } on OutOfLlamasException { buyMoreLlamas(); }

To handle code that can throw more than one type of exception, you can specify multiple catch clauses. The first catch clause that matches the thrown object’s type handles the exception. If the catch clause does not specify a type, that clause can handle any type of thrown object:

try { breedMoreLlamas(); } on OutOfLlamasException { // A specific exception buyMoreLlamas(); } on Exception catch (e) { // Anything else that is an exception print('Unknown exception: $e'); } catch (e) { // No specified type, handles all print('Something really unknown: $e'); }

As the preceding code shows, you can use either or or both. Use when you need to specify the exception type. Use when your exception handler needs the exception object.

You can specify one or two parameters to . The first is the exception that was thrown, and the second is the stack trace (a object).

To partially handle an exception, while allowing it to propagate, use the keyword.


To ensure that some code runs whether or not an exception is thrown, use a clause. If no clause matches the exception, the exception is propagated after the clause runs:

try { breedMoreLlamas(); } finally { // Always clean up, even if an exception is thrown. cleanLlamaStalls(); }

The clause runs after any matching clauses:

try { breedMoreLlamas(); } catch (e) { print('Error: $e'); // Handle the exception first. } finally { cleanLlamaStalls(); // Then clean up. }

Learn more by reading the Exceptions section of the library tour.


Dart is an object-oriented language with classes and mixin-based inheritance. Every object is an instance of a class, and all classes except descend from . Mixin-based inheritance means that although every class (except for the top class, ) has exactly one superclass, a class body can be reused in multiple class hierarchies. Extension methods are a way to add functionality to a class without changing the class or creating a subclass.

Using class members

Objects have members consisting of functions and data (methods and instance variables, respectively). When you call a method, you invoke it on an object: the method has access to that object’s functions and data.

Use a dot () to refer to an instance variable or method:

var p = Point(2, 2); // Get the value of y. assert(p.y == 2); // Invoke distanceTo() on p. double distance = p.distanceTo(Point(4, 4));

Use instead of to avoid an exception when the leftmost operand is null:

// If p is non-null, set a variable equal to its y value. var a = p?.y;

Using constructors

You can create an object using a constructor. Constructor names can be either or . For example, the following code creates objects using the and constructors:

var p1 = Point(2, 2); var p2 = Point.fromJson({'x': 1, 'y': 2});

The following code has the same effect, but uses the optional keyword before the constructor name:

var p1 = new Point(2, 2); var p2 = new Point.fromJson({'x': 1, 'y': 2});

Some classes provide constant constructors. To create a compile-time constant using a constant constructor, put the keyword before the constructor name:

var p = const ImmutablePoint(2, 2);

Constructing two identical compile-time constants results in a single, canonical instance:

var a = const ImmutablePoint(1, 1); var b = const ImmutablePoint(1, 1); assert(identical(a, b)); // They are the same instance!

Within a constant context, you can omit the before a constructor or literal. For example, look at this code, which creates a const map:

// Lots of const keywords here. const pointAndLine = const { 'point': const [const ImmutablePoint(0, 0)], 'line': const [const ImmutablePoint(1, 10), const ImmutablePoint(-2, 11)], };

You can omit all but the first use of the keyword:

// Only one const, which establishes the constant context. const pointAndLine = { 'point': [ImmutablePoint(0, 0)], 'line': [ImmutablePoint(1, 10), ImmutablePoint(-2, 11)], };

If a constant constructor is outside of a constant context and is invoked without , it creates a non-constant object:

var a = const ImmutablePoint(1, 1); // Creates a constant var b = ImmutablePoint(1, 1); // Does NOT create a constant assert(!identical(a, b)); // NOT the same instance!

Getting an object’s type

To get an object’s type at runtime, you can use the property , which returns a object.

print('The type of a is ${a.runtimeType}');

Use a type test operator rather than to test an object’s type. In production environments, the test is more stable than the test .

Up to here, you’ve seen how to use classes. The rest of this section shows how to implement classes.

Instance variables

Here’s how you declare instance variables:

class Point { double? x; // Declare instance variable x, initially null. double? y; // Declare y, initially null. double z = 0; // Declare z, initially 0. }

All uninitialized instance variables have the value .

All instance variables generate an implicit getter method. Non-final instance variables and instance variables without initializers also generate an implicit setter method. For details, see Getters and setters.

If you initialize a non- instance variable where it’s declared, the value is set when the instance is created, which is before the constructor and its initializer list execute.

class Point { double? x; // Declare instance variable x, initially null. double? y; // Declare y, initially null. } void main() { var point = Point(); point.x = 4; // Use the setter method for x. assert(point.x == 4); // Use the getter method for x. assert(point.y == null); // Values default to null. }

Instance variables can be , in which case they must be set exactly once. Initialize , non- instance variables at declaration, using a constructor parameter, or using a constructor’s initializer list:

class ProfileMark { final String name; final DateTime start =; ProfileMark(; ProfileMark.unnamed() : name = ''; }

If you need to assign the value of a instance variable after the constructor body starts, you can use one of the following:


Declare a constructor by creating a function with the same name as its class (plus, optionally, an additional identifier as described in Named constructors). The most common form of constructor, the generative constructor, creates a new instance of a class:

class Point { double x = 0; double y = 0; Point(double x, double y) { // There's a better way to do this, stay tuned. this.x = x; this.y = y; } }

The keyword refers to the current instance.

Note: Use only when there is a name conflict. Otherwise, Dart style omits the .

The pattern of assigning a constructor argument to an instance variable is so common, Dart has syntactic sugar to make it easy:

class Point { double x = 0; double y = 0; // Syntactic sugar for setting x and y // before the constructor body runs. Point(this.x, this.y); }

Default constructors

If you don’t declare a constructor, a default constructor is provided for you. The default constructor has no arguments and invokes the no-argument constructor in the superclass.

Constructors aren’t inherited

Subclasses don’t inherit constructors from their superclass. A subclass that declares no constructors has only the default (no argument, no name) constructor.

Named constructors

Use a named constructor to implement multiple constructors for a class or to provide extra clarity:

Remember that constructors are not inherited, which means that a superclass’s named constructor is not inherited by a subclass. If you want a subclass to be created with a named constructor defined in the superclass, you must implement that constructor in the subclass.

Invoking a non-default superclass constructor

By default, a constructor in a subclass calls the superclass’s unnamed, no-argument constructor. The superclass’s constructor is called at the beginning of the constructor body. If an initializer list is also being used, it executes before the superclass is called. In summary, the order of execution is as follows:

  1. initializer list
  2. superclass’s no-arg constructor
  3. main class’s no-arg constructor

If the superclass doesn’t have an unnamed, no-argument constructor, then you must manually call one of the constructors in the superclass. Specify the superclass constructor after a colon (), just before the constructor body (if any).

In the following example, the constructor for the Employee class calls the named constructor for its superclass, Person. Click Run to execute the code.

Because the arguments to the superclass constructor are evaluated before invoking the constructor, an argument can be an expression such as a function call:

class Employee extends Person { Employee() : super.fromJson(fetchDefaultData()); // ··· }

Warning: Arguments to the superclass constructor don’t have access to . For example, arguments can call static methods but not instance methods.

Initializer list

Besides invoking a superclass constructor, you can also initialize instance variables before the constructor body runs. Separate initializers with commas.

// Initializer list sets instance variables before // the constructor body runs. Point.fromJson(Map<String, double> json) : x = json['x']!, y = json['y']! { print('In Point.fromJson(): ($x, $y)'); }

Warning: The right-hand side of an initializer doesn’t have access to .

During development, you can validate inputs by using in the initializer list.

Initializer lists are handy when setting up final fields. The following example initializes three final fields in an initializer list. Click Run to execute the code.

Redirecting constructors

Sometimes a constructor’s only purpose is to redirect to another constructor in the same class. A redirecting constructor’s body is empty, with the constructor call (using instead of the class name) appearing after a colon (:).

class Point { double x, y; // The main constructor for this class. Point(this.x, this.y); // Delegates to the main constructor. Point.alongXAxis(double x) : this(x, 0); }

Constant constructors

If your class produces objects that never change, you can make these objects compile-time constants. To do this, define a constructor and make sure that all instance variables are .

class ImmutablePoint { static const ImmutablePoint origin = ImmutablePoint(0, 0); final double x, y; const ImmutablePoint(this.x, this.y); }

Constant constructors don’t always create constants. For details, see the section on using constructors.

Factory constructors

Use the keyword when implementing a constructor that doesn’t always create a new instance of its class. For example, a factory constructor might return an instance from a cache, or it might return an instance of a subtype. Another use case for factory constructors is initializing a final variable using logic that can’t be handled in the initializer list.

Tip: Another way to handle late initialization of a final variable is to use (carefully!).

In the following example, the factory constructor returns objects from a cache, and the factory constructor initializes a final variable from a JSON object.

class Logger { final String name; bool mute = false; // _cache is library-private, thanks to // the _ in front of its name. static final Map<String, Logger> _cache = <String, Logger>{}; factory Logger(String name) { return _cache.putIfAbsent( name, () => Logger._internal(name)); } factory Logger.fromJson(Map<String, Object> json) { return Logger(json['name'].toString()); } Logger._internal(; void log(String msg) { if (!mute) print(msg); } }

Note: Factory constructors have no access to .

Invoke a factory constructor just like you would any other constructor:

var logger = Logger('UI'); logger.log('Button clicked'); var logMap = {'name': 'UI'}; var loggerJson = Logger.fromJson(logMap);


Methods are functions that provide behavior for an object.

Instance methods

Instance methods on objects can access instance variables and . The method in the following sample is an example of an instance method:

import 'dart:math'; class Point { double x = 0; double y = 0; Point(this.x, this.y); double distanceTo(Point other) { var dx = x - other.x; var dy = y - other.y; return sqrt(dx * dx + dy * dy); } }


Operators are instance methods with special names. Dart allows you to define operators with the following names:

Note: You may have noticed that some operators, like , aren’t in the list of names. That’s because they’re just syntactic sugar. For example, the expression is syntactic sugar for .

An operator declaration is identified using the built-in identifier . The following example defines vector addition () and subtraction ():

class Vector { final int x, y; Vector(this.x, this.y); Vector operator +(Vector v) => Vector(x + v.x, y + v.y); Vector operator -(Vector v) => Vector(x - v.x, y - v.y); // Operator == and hashCode not shown. // ··· } void main() { final v = Vector(2, 3); final w = Vector(2, 2); assert(v + w == Vector(4, 5)); assert(v - w == Vector(0, 1)); }

Getters and setters

Getters and setters are special methods that provide read and write access to an object’s properties. Recall that each instance variable has an implicit getter, plus a setter if appropriate. You can create additional properties by implementing getters and setters, using the and keywords:

class Rectangle { double left, top, width, height; Rectangle(this.left,, this.width, this.height); // Define two calculated properties: right and bottom. double get right => left + width; set right(double value) => left = value - width; double get bottom => top + height; set bottom(double value) => top = value - height; } void main() { var rect = Rectangle(3, 4, 20, 15); assert(rect.left == 3); rect.right = 12; assert(rect.left == -8); }

With getters and setters, you can start with instance variables, later wrapping them with methods, all without changing client code.

Note: Operators such as increment (++) work in the expected way, whether or not a getter is explicitly defined. To avoid any unexpected side effects, the operator calls the getter exactly once, saving its value in a temporary variable.

Abstract methods

Instance, getter, and setter methods can be abstract, defining an interface but leaving its implementation up to other classes. Abstract methods can only exist in abstract classes.

To make a method abstract, use a semicolon (;) instead of a method body:

abstract class Doer { // Define instance variables and methods... void doSomething(); // Define an abstract method. } class EffectiveDoer extends Doer { void doSomething() { // Provide an implementation, so the method is not abstract here... } }

Abstract classes

Use the modifier to define an abstract class—a class that can’t be instantiated. Abstract classes are useful for defining interfaces, often with some implementation. If you want your abstract class to appear to be instantiable, define a factory constructor.

Abstract classes often have abstract methods. Here’s an example of declaring an abstract class that has an abstract method:

// This class is declared abstract and thus // can't be instantiated. abstract class AbstractContainer { // Define constructors, fields, methods... void updateChildren(); // Abstract method. }

Implicit interfaces

Every class implicitly defines an interface containing all the instance members of the class and of any interfaces it implements. If you want to create a class A that supports class B’s API without inheriting B’s implementation, class A should implement the B interface.

A class implements one or more interfaces by declaring them in an clause and then providing the APIs required by the interfaces. For example:

// A person. The implicit interface contains greet(). class Person { // In the interface, but visible only in this library. final String _name; // Not in the interface, since this is a constructor. Person(this._name); // In the interface. String greet(String who) => 'Hello, $who. I am $_name.'; } // An implementation of the Person interface. class Impostor implements Person { String get _name => ''; String greet(String who) => 'Hi $who. Do you know who I am?'; } String greetBob(Person person) => person.greet('Bob'); void main() { print(greetBob(Person('Kathy'))); print(greetBob(Impostor())); }

Here’s an example of specifying that a class implements multiple interfaces:

class Point implements Comparable, Location {...}

Extending a class

Use to create a subclass, and to refer to the superclass:

For another usage of , see the discussion of parameterized types in generics.

Overriding members

Subclasses can override instance methods (including operators), getters, and setters. You can use the annotation to indicate that you are intentionally overriding a member:

An overriding method declaration must match the method (or methods) that it overrides in several ways:

  • The return type must be the same type as (or a subtype of) the overridden method’s return type.
  • Argument types must be the same type as (or a supertype of) the overridden method’s argument types. In the preceding example, the setter of changes the argument type from to a supertype, .
  • If the overridden method accepts n positional parameters, then the overriding method must also accept n positional parameters.
  • A generic method can’t override a non-generic one, and a non-generic method can’t override a generic one.

Sometimes you might want to narrow the type of a method parameter or an instance variable. This violates the normal rules, and it’s similar to a downcast in that it can cause a type error at runtime. Still, narrowing the type is possible if the code can guarantee that a type error won’t occur. In this case, you can use the keyword in a parameter declaration. For details, see the Dart language specification.

Warning: If you override , you should also override Object’s getter. For an example of overriding and , see Implementing map keys.


To detect or react whenever code attempts to use a non-existent method or instance variable, you can override :

You can’t invoke an unimplemented method unless one of the following is true:

  • The receiver has the static type .

  • The receiver has a static type that defines the unimplemented method (abstract is OK), and the dynamic type of the receiver has an implementation of that’s different from the one in class .

For more information, see the informal noSuchMethod forwarding specification.

Extension methods

Extension methods are a way to add functionality to existing libraries. You might use extension methods without even knowing it. For example, when you use code completion in an IDE, it suggests extension methods alongside regular methods.

Here’s an example of using an extension method on named that’s defined in :

For details of using and implementing extension methods, see the extension methods page.

Enumerated types

Enumerated types, often called enumerations or enums, are a special kind of class used to represent a fixed number of constant values.

Using enums

Declare an enumerated type using the keyword:

enum Color { red, green, blue }

You can use trailing commas when declaring an enumerated type.

Each value in an enum has an getter, which returns the zero-based position of the value in the enum declaration. For example, the first value has index 0, and the second value has index 1.

assert( == 0); assert( == 1); assert( == 2);

To get a list of all of the values in the enum, use the enum’s constant.

List<Color> colors = Color.values; assert(colors[2] ==;

You can use enums in switch statements, and you’ll get a warning if you don’t handle all of the enum’s values:

var aColor =; switch (aColor) { case print('Red as roses!'); break; case print('Green as grass!'); break; default: // Without this, you see a WARNING. print(aColor); // '' }

Enumerated types have the following limits:

  • You can’t subclass, mix in, or implement an enum.
  • You can’t explicitly instantiate an enum.

For more information, see the Dart language specification.


5263 5264 5265 5266 5267