Dart is an object-orientated language with class-based inheritance similar to Java or C#. All types descend from the base Object class. The var keyword declares a variable and is a substitute for a strong type annotation. Variables must be declared before they are used (unlike JavaScript), and objects created by using the new keyword to invoke the object's constructor:
var myObject = new Object(); // declare myObject and
// construct the Object
print(myObject); // use the object
All objects inherit the Object.hashCode() and Object.toString() methods. The toString() method is called automatically whenever you try and convert an object into a string representation, such as when using the print() function:
// equivalent
print(123);
print(123.toString());
Stylistically using the var keyword for variable declaration should be preferred within code bodies. Only use explicit type annotations (such as String, int) at the "surface area" of your code, for example, in function parameter lists, return types, and class properties.
Dart has special support for a number of core, "primitive" types that are baked into the language. Although these types are objects, extending from the Object base class, you create instances of these objects literally, without using the new keyword.
num, int, double
num is the base numeric type, and has two implementations: int and double. num declares the basic operators of +-/* and functions such as abs(), ceil(), floor(), and round(), amongst others.
num
Use num to declare that you want a numeric value, whether an integer or floating-point.
num myNum = 123.45;
num myRounded = myNum.round();
int
The int type accepts integer values of arbitrary precision:
int myInt = 123;
// or
var myInt = 456;
var myIntAsHex = 0xABCDEF12345;
var myBigInt = 65498763215487654321654987654321354987;
double
The double type accepts 64-bit floating point numbers as specified in the IEEE 754 standard:
double myDouble = 123.45;
// or
var myDouble = 123.45;
var myDoubleWithExponent = 1.23e4;
bool
In Dart, only the literal boolean true is considered true. All other values are false. An extra restriction in checked mode only allows boolean operations on true and false literal values.
bool myTrue = true;
// or
var myTrue = true;
var myFalse = false;
print(myTrue == myFalse); // equals: false
print(myTrue != myFalse); // not equals: true
print(myTrue == myFalse || myTrue == myTrue) // or: true
print(myTrue && myTrue) // and: true
You can us the is and is! syntax to check a type's instance:
print("I am a string" is String) // prints "true"
print("I am not an int" is! int) // prints "true"
String
Dart strings are declared with either single or double quotes, and you can mix strings containing either:
String myString = "double quoted";
var myString = 'single quoted';
var myString = "contains 'single' quote";
var myString='contains "double" quote';
Multi-line strings are declared with three double-quotes:
var myString = """This is
a multi-line
string and can contain "double" and 'single' quotes""";
Strings can also contain escape codes, such as \n for new line:
var myString = "Line 1\nLine 2";
But you can also declare a raw string that will ignore escape codes by using the prefix r.
var myString = r"Line1\nStill line 1";
String interpolation
Dart strings cannot be concatenated using the + operator. The following code is not valid:
var myString = "hello" + " world"; // invalid syntax!
Instead, you must use string interpolation, which converts variables or expressions embedded within a string into a string. The following embeds two variables into a string by prefixing the variable name with $:
var greeting = "Hello";
var audience = "World";
var message = "$greeting $audience";
print(message); // Hello World
An expression enclosed within ${…} is evaluated before it is inserted into the string, for example:
var answer = "result=${1+2}";
print(answer); // result=3
The expression contained within curly braces can be any valid Dart expression, including function calls, for example:
var answer = "result=${1.23.round()}";
print(answer); // result=1.0
List
Dart doesn't have an explicit array type. Instead, it has a List type, which you can declare using either literal syntax, or as a List object. Internally, the object is the same.
// using list literal syntax
List myList = []; // empty list
or
var myList = []; // empty list
var myList = [1,2,3,4]; // all int values
var myList = ["Item 1", "Item 2", 3, 4]; // mixed values
// using List object constructor
List myList = new List(); // empty list
or
var myList = new List(); // empty list
var myList = new List(10); // list containing 10 nulls
var myList = new List.filled(10,"AA"); // contains 10
// "AA" strings
You can add items to these lists by using the add() method, and access values using zero-based indexer syntax [ ]. Use the length property to discover how many items are in the list:
var myList = [];
myList.add("item 1");
myList.add("item 2");
myList[0] = "ITEM 1"; // replaces "item 1";
print(myList[1]) // "item 2";
print(myList.length); // 2
Lists can also be fixed size by using the List.fixedLength() constructor. Lists created in this way cannot have items added to them.
var myList = new List.fixedLength(10); // fixed length
myList.add("item11"); // throws UnsupportedError
// create a fixed length list where each element is filled with the string "AA"
var myList = new List.fixedLength(10,fill="AA");
Using Generics
Lists allow use of generic types. This means that you can use type annotations to tell Dart and fellow developers that you are expecting your list to contain only certain types. For example, the following list should contain only Strings. Adding an integer would raise a type warning.
var myList = new List<String>();
myList.add(123); // warning: 123 is not a String
var myList = <String>["a","b"];
myList.add(123); // warning: 123 is not a String
Iterating Lists with a for loop
You can use the standard for loop to iterate a list. The syntax is similar to Java, JavaScript, and C#. This is useful if you want to replace the item at each index:
var myList = [1,2,3];
for (var index=0; index<myList.length; index++) {
var value = myList[index];
myList[index] = value * value; // store the new value
}
Iterating Lists with for-in
You can use a for-in construct to access each item in the list:
var myList = ["hello","world"];
for (var item in myList) {
print(item);
}
Iterating Lists with forEach
You can also iterate a list by using a forEach function callback, which calls a function, passing the function each item in the list:
var myList = ["hello", "world"];
myList.forEach( (item) { //
print(item); // anonymous function callback
} ); //
(See the section on Functions for more detailed explanation of anonymous functions).
Other collections
Other collection classes include HashSet, Queue and Set, which offer more specialized functionality
Map
Like Lists, you can create maps (comma-separated list of key:value pairs) using either a map literal or a class constructor:
// Map Literal syntax
Map myMap = {"key1":"value1", "key2":"value2"};
// or
var myMap = {"key1":"value1", "key2":"value2"};
var myMap = {}; // empty map
// Map constructor syntax
Map myMap = new Map(); // empty map
// or
var myMap = new Map(); // empty map
Using Generics
Any type can be used as a map's key or a value, and you can mix key and value types within a map. To restrict the key or value types, you can create maps using Generic typing (as with Lists)
// key is String, value is any Object
var myMap = <String,Object>{}; // empty map
var myMap = new Map<String,Object>();
You access and insert items into a map by using a key as an indexer. If the key does not already exist, it will be replaced.
var myMap = new Map();
myMap["key1"] = "value1";
myMap["key2"] = "value2";
print(myMap["key2"]); // value2
Accessing a key that has not been added will return null, but you can also explicitly check if the key exists using the containsKey() method.
var myMap = {"key1":"value1"};
print(myMap["key2"]); // null
print(myMap,containsKey["key2"]); // false
You can easily access a map's keys and values properties:
var myMap = {"key1":"value1", "key2":"value2"};
// access the keys
for (var key in myMap.keys) {
print(key);
}
// access the values
for (var value in myMap.values) {
print(value);
}
You can also iterate the key:value pairs using a forEach function callback:
var myMap = {"key1":"value1", "key2":"value2"};
myMap.forEach( (key, value) { //
print("$key = $value"); // anonymous callback
} );
{{ parent.title || parent.header.title}}
{{ parent.tldr }}
{{ parent.linkDescription }}
{{ parent.urlSource.name }}