Built-in types

The Dart language supports the following:

  • Numbers (int.double)
  • Strings (String)
  • Booleans (bool)
  • Lists(Also known asarrays)
  • Sets (Set)
  • Maps (Map)
  • RunesOften used inCharactersCharacter substitution in API)
  • Symbols (Symbol)
  • The value null (Null)

The use of literals to create objects is also supported. For example, ‘This is a string’ is a string literal, true is a Boolean literal.

Because each variable reference in Dart points to an object (an instance of a class), you can often use a constructor to initialize variables as well. Some built-in types have their own constructors. For example you can use Map() to create a Map object.

Other types also have special roles in the Dart language:

  • Object: Superclass for all Dart classes except Null.
  • The Future and the Stream: used for asynchronous support.
  • 可迭代: used in for-in loops and synchrogenerator functions.
  • Never: indicates that the expression never completes evaluation successfully. Most commonly used for functions that always throw an exception.
  • dynamic: Disables static check. Usually you should use Object or Object? Instead.
  • void: indicates that a value is never used. Commonly used as a return type.

Numbers

Dart supports two Number types:

  • int

    The integer value; The value contains a maximum of 64 characters and varies with platforms. On DartVM, the value is between -263 and 263-1. On the Web, integer values represent JavaScript numbers (64-bit, decimal-free floating-point) that are allowed in the range of -253 to 253-1.

  • double

    A 64-bit double – precision floating – point number that complies with IEEE 754 standards.

Int and double are subclasses of [num]. Num defines basic operators such as +, -, *, /, etc., as well as methods such as ABS (), ceil(), and floor() (bitwise operators such as >> are defined in int). If num and its subclasses don’t meet your requirements, look at the API in the DART: Math library.

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

var x = 1;
var hex = 0xDEADBEEF;
var exponent = 8e5;
Copy the code

If a number contains a decimal point, it is floating-point. Here are some examples of defining dimensions for floating-point numbers:

var y = 1.1;
var exponents = 1.42 e5;
Copy the code

You can also declare the variable num, and if you do, the variable can have both an integer and a double value

num x = 1; // x can have both an int and a double
x += 2.5;
Copy the code

Integer literals are automatically converted to floating-point numbers when necessary:

double z = 1; // Double z = 1.0.
Copy the code

Prior to Dart 2.1, it was an error to use integer literals in the context of floating point numbers. For more, check out the numbers in Dart.

Strings

The Dart String (String object) contains a sequence of UTF-16 encoded characters. Strings can be created using either single or double quotation marks:

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.";
Copy the code

In a string, use the expression as ${expression}, or omit {} if the expression is an identifier. If the expression results in an object, Dart calls the object’s toString method to get a string.

// Code interpretation
var s = 'String interpolation';
assert('Dart is$sIt is very convenient to use. '= ='Dart has string interpolation and is very easy to use. ');
assert('use${s.substring(3.5)}The expression is also very handy.= ='Interpolation is also very convenient. ');
Copy the code

The == operator determines whether the contents of two objects are the same. If two strings contain the same sequence of character encodings, they are equal. You can concatenate strings using the + operator or by placing multiple strings side by side:

// Code interpretation
var s1 = 'Spliced'
    'String'
    "Even if they're not on the same line.";
print(s1 == 'can concatenate strings even if they are not on the same line. ');

var s2 = 'Use the plus + operator' + 'can achieve the same effect. ';
print(s2 == The same effect can be achieved using the plus + operator. ');
Copy the code

It is also possible to create a multi-line string using three single quotes or three double quotes:

// Code interpretation
  var s5 = You can create a multi-line string like this.;
  var s6 = """ You can create multi-line strings like this;
  print(s5 == s6); // true
Copy the code

Prefixes the string with r to create a “raw” string (that is, a string that will not be processed (such as escaped)) :

var s = R 'In raw strings, the escaped string \n will print "\n" directly instead of escaping to a newline. ';
print(s); // In raw strings, the escaped string \n will print "\n" directly instead of escaping to a newline. \
Copy the code

You can consult Runes and Grapheme Clusters for more information on how to represent Unicode characters in strings.

A string literal is a compile-time constant, and any compile-time constant (NULL, number, string, Boolean) can be used as an interpolation for a string literal:

// 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';
Copy the code

See strings and regular expressions for more information on how to use strings.

Boolean type

Dart uses the bool keyword to represent Boolean types, which have only two objects, true and false, both of which are compile-time constants.

Dart’s type safety does not allow you to check booleanvalues with code like if (nonbooleanValue) or Assert (nonbooleanValue). Instead, you should always check booleans explicitly, as in the following code:

// Check for empty strings.
var fullName = ' ';
print(fullName.isEmpty); // true

// Check the value of 0.
var hitPoints = 0;
print(hitPoints <= 0); // true

// Check for null values.
var unicorn;
print(unicorn == null); // true

// Check NaN.
var iMeantToDoThis = 0 / 0;
print(iMeantToDoThis.isNaN); // true
Copy the code

Lists

Arrays are the most common collection type in almost all programming languages, and arrays in Dart are represented by List objects. It’s usually called a List.

The List literal in Dart looks like the array literal in JavaScript. Here is an example of a Dart List:

var list = [1.2.3];
Copy the code

Dart infer that list is of type list

, and an error is reported if you add a non-int object to the array. You can read type inference for more information.

You can add a comma after the last item of Dart’s collection type. The trailing comma does not affect the collection, but it is useful to avoid copy-and-paste errors.

var list = ['Car'.'Boat'.'Plane',];
Copy the code

The index of List starts at 0, the index of the first element is 0, and the index of the last element is list.length-1. You can get the length and elements of the List in Dart as we do in JavaScript:

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

list[1] = 1;
assert(list[1] = =1);
Copy the code

Adding the const keyword to the List literal creates a compile-time constant:

var constantList = const [1.2.3];
// constantList[1] = 1; // This line will cause an error.
Copy the code

Create a final instance variable. Final objects cannot be modified, but their fields can be modified:

final list = [1.2.3];
var constantList = list;
constantList[1] = 1; 
print(constantList); / / [1, 1, 3]
Copy the code

List applies the extension operator.and. ?

Dart introduced the extension operator in 2.3 (…) And null-aware extension operators (… ?). , they provide a neat way to insert multiple elements into a collection. You can use the extension operator (…) Insert all elements from one List into another List:

var list = [1.2.3];
var list2 = [0. list];assert(list2.length == 4);
Copy the code

If the right side of the extension operator may be NULL, you can use the null-aware extension operator (… ?). To avoid generating exceptions:

var list;
var list2 = [0. ? list];assert(list2.length == 1);
Copy the code

See extension operator advice for more information on how to use extension operators.

Dart also introduces both the if in collections and the for operation in collections, allowing you to use conditional judgments (if) and loops (for) when building collections.

The following example is an example of using if from a collection to create a List, which may contain three or four elements:

var nav = [
  'Home'.'Furniture'.'Plants'.if (promoActive) 'Outlet'
];
Copy the code

Here is an example of adding a modified element from a list to another list using for in a collection:

var listOfInts = [1.2.3];
var listOfStrings = [
  '# 0'.for (var i in listOfInts) '#$i'
];
assert(listOfStrings[1] = ='# 1');
Copy the code

For more details and examples of using if and for in collections, see using Control Flow advice in collections.

The List class has many handy ways to manipulate lists, and you can consult generics and collections for more information about them.

Sets

In Dart, a set is a uniquely unordered set of elements. The collections supported by Dart are provided by the literals of the collection and the Set class.

Although Set types have always been a core feature of Dart, Set literals were added in Dart 2.2.

Here’s how to create a Set using a Set literal:

var halogens = {'fluorine'.'chlorine'.'bromine'.'iodine'.'astatine'};
Copy the code

Dart deduces that the Halogens variable is a Set of type Set

, and an error is reported if you add an incorrectly typed object to that Set. You can check out type inference for more on this.

We can create an empty Set by prefixing {} with a type argument, or assign {} to a variable of type Set:

var names = <String> {};// Set
      
        names = {}; // This is ok.
      
// var names = {}; // This creates a Map instead of a Set.
Copy the code

The Set or the map? The Map literal syntax is similar to the Set literal syntax. Because of the Map literal syntax, {} defaults to Map. If you forget to comment out a type on {} or assign a value to an undeclared variable, Dart creates an object of type Map

.
,>

Add an item to an existing Set using the add() or addAll() method:

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

Use.length to get the number of elements in a Set:

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

We can create a compile-time constant by adding the const keyword to a Set variable:

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

Starting with Dart 2.3, sets can support the use of extended operators like lists (… And… ?). And Collection if and for operations. You can consult the List extension operator and the List collection operator for more information.

You can also refer to generics and sets for more information.

Maps

In general, a Map is an object used to associate keys and values. Where keys and values can be objects of any type. Each key can only appear once but the value can be repeated many times. Dart maps provide two types of maps: Map literals and Map types.

Here are a couple of examples of creating a Map using a Map literal:

var gifts = {
    // Key: Value
    'first': 'partridge'.'second': 'turtledoves'.'fifth': 'golden rings'
};

var nobleGases = {
    2: 'helium'.10: 'neon'.18: 'argon'};Copy the code

Dart deduces the gifts variable type to Map

, and nobleGases type to Map

. If you add incorrect type values to the two Map objects, it will cause a runtime exception. You can read type inference for more information.
,>
,>

You can also create a Map using the 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';
Copy the code

If you used C# or Java before, you might want to construct a Map object using new Map(). But in Dart, the new keyword is optional. You can refer to the use of constructors for more information.

Adding key-value pairs to an existing Map is similar to JavaScript:

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

Retrieving a value from a Map is also similar to JavaScript:

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

A null is returned if the retrieved Key does not exist in the Map:

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

Use.length to get the number of key-value pairs in the Map:

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

Adding the const keyword to a Map literal creates a Map compile-time constant:

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

Maps, like lists, can support the use of extension operators (… And… ?). And the if and for operations on collections. You can consult the List extension operator and the List collection operator for more information.

You can also check out the generics and Maps API for more information.

With Runes and grapheme clusters

In Dart, Runes exposes Unicode code points for strings. The characters package is used to access and manipulate user-aware characters, also known as Unicode (extended) Grapheme clusters.

The Unicode encoding defines a unique numeric value for each letter, number, and symbol. Because the string in Dart is a SEQUENCE of UTF-16 characters, a special syntax is required if you want to represent 32-bit Unicode values.

A common way to represent Unicode characters is to use \uXXXX, where XXXX is a four-digit hexadecimal number. For example, the Unicode for the heart character (♥) is \u2665. For hexadecimal numbers that are not four digits, you need to enclose them in braces. For example, the laughing emoji (😆) has Unicode \u{1f600}.

If you need to read and write individual Unicode characters, use the Characters getter defined in the Characters package. It returns the Characters object as a string of Grapheme clusters. Here’s an example using the Characters API:

import 'package:characters/characters.dart'; .var hi = 'Hi 🇩 🇰';
print(hi);
print('The end of the string: ${hi.substring(hi.length - 1)}');
print('The last character: ${hi.characters.last}\n');
Copy the code

The output depends on your environment and looks something like this:

Dart Hi 🇩🇰 The end of The string:?? The last character: 🇩 🇰Copy the code

For more information about manipulating strings with the Characters package, see the sample and API reference for the Characters package.

Be careful when using Rune with List. Depending on the language, character set, etc., this can cause string problems. [How do I reverse a String in Dart?] .

Symbols

Symbol represents the declared operator or identifier in Dart. You almost never need symbols, but they are useful for apis that refer to identifiers by name, because when the code is compressed, the identifiers’ names change, but their symbols remain the same.

We can obtain the Symbol by prefixing the identifier with # :

#radix
#bar
Copy the code

The Symbol literal is a compile-time constant.