The Dart language supports the following built-in types:
- Number
- String
- Boolean
- List (also known as Array)
- Map
- Set
- Rune (used to represent Unicode characters in strings)
- Symbol
These types can all be initialized to literals. Such as: Boolean literals [1,2,3] array literals {a:1, B :2,c:3} object literals Because in Dart all variables are after all an object (an instance of a class), So variables can be initialized using a construct culvert number. Some built-in types have their own constructors. For example, construct a Map variable with Map()
Number
There are two types of numbers in the Dart language
num a1 = 1.22;
num a2 = 1;
int b = 1;
double c = 1.0;
Copy the code
int
Integer values are not greater than 64 bits, depending on the platform. On the Dart VM, the values can range from -2 to 2-1. Dart compiled into JavaScript uses JavaScript numbers, allowing values from -2 to 2-1
double
A 64-bit (double) floating-point number. Int and double are both subtypes of num according to IEEE 754. The num types include basic operations +, -, /, and *, as well as abs(), ceil(), and floor(), and other function methods. (Bitwise operators, such as », are defined in the int class.) If num and its subtypes can’t find the method you want, try looking using the Dart: Math library. The integer type does not contain a decimal point. Here is an example of defining integer type literals:
var x = 1;
var hex = 0xDEADBEEF;
Copy the code
If a number contains a decimal point, it is of decimal type. Here is an example of defining decimal-type literals:
var y = 1.1;
var exponents = 1.42 e5;
Copy the code
Starting with Dart 2.1, int literals are automatically converted to double when necessary
double z = 1; // Double z = 1.0.
Copy the code
**⚠️ version tip: ** Before 2.1, it was an error to use an int literal in the context of double
Here’s how to convert a string to a number and 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');
Copy the code
Int the unique traditional bitwise operation, the operation shift (< <, > >) and bitwise and (&) and bitwise or (|). Such as:
assert((3 << 1) = =6); // 0011 << 1 == 0110
assert((3 >> 1) = =1); // 0011 >> 1 == 0001
assert((3 | 4) = =7); / / 0011 | 0100 = = 0111
Copy the code
Numeric type literals are compile-time constants. In an arithmetic expression, the result of an arithmetic expression is a compile-time constant as long as the factors involved in the evaluation are compile-time constants.
const msPerSecond = 1000;
const secondsUntilRetry = 5;
const msUntilRetry = secondsUntilRetry * msPerSecond;
Copy the code
String
The Dart string is a sequence of UTF-16 units. Strings are created using 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
Strings can be nested with expressions as ${expression}. If the expression is an identifier, {} can be omitted. Dart retrieves the string of the object by calling the toString() method on the object.
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! ');
Copy the code
⚠️ Note: The == operator tests whether two objects are equal. In a string, two strings are equal if they contain the same encoding sequence
String concatenation can be achieved by using the + operator to concatenate multiple strings into one, or by writing multiple literal strings together:
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.');
Copy the code
Create a multi-line string object with three consecutive single or double quotes:
var s1 = '''
You can create
multi-line strings like this one.
''';
var s2 = """This is also a
multi-line string.""";
Copy the code
Using the r prefix, you can create “raw” strings:
var s = r"In a raw string, even \n isn't special.";
Copy the code
Refer to Runes to learn how to express Unicode characters in strings.
A literal string of compile-time constants is a compile-time constant if interpolation is present and the expression content is compile-time constant. The inserted constant value type can be NULL, numeric, string, or Boolean
// Const type data
const aConstNum = 0;
const aConstBool = true;
const aConstString = 'a constant string';
// Nonconst data
var aNum = 0;
var aBool = true;
var aString = 'a string';
const aConstList = [1.2.3];
const validConstString = '$aConstNum $aConstBool $aConstString'; // Const type data
// const invalidConstString = '$aNum $aBool $aString $aConstList'; // Nonconst data
Copy the code
For more on the use of strings, see strings and regular expressions
Boolean
Dart uses type bool to represent a Boolean value. Dart only has literals true and false, which are Boolean types. Both objects are compile-time constants. Dart’s type-safety means that you cannot use if (nonbooleanValue) or Assert (nonbooleanValue). Instead, the value check should be explicitly done as follows:
// Check for empty strings.
var fullName = ' ';
assert(fullName.isEmpty);
// Check the value of 0.
var hitPoints = 0;
assert(hitPoints <= 0);
// Check for null values.
var unicorn;
assert(unicorn == null);
// Check NaN.
var iMeantToDoThis = 0 / 0;
assert(iMeantToDoThis.isNaN);
Copy the code
List
Probably the most common collection in almost every programming language is an array or an ordered collection of objects. An Array in Dart is a List object, usually called a List. A List is one of the Dart collection types, but you can think of it simply as an Array (that’s what I think of it anyway)
The List literal in Dart looks a lot like the array literal in JavaScript. Here is a Dart List declaration with several examples:
var myList = List(): non-fixed length declarationvar myList = List(2): fixed length statementvar myList= List<String>(): fixed type declarationvar myList = [1.2.3] :ListDirect assignmentCopy the code
⚠️ Note: Dart inferred that the list is of type list. If you try to add a non-integer object to this List, the parser or runtime will raise an error. For more information, read Type inference.
The subscript index of Lists starts at 0 and the first element has an index of 0. List.length-1 is the index of the last element. The length and elements of the access List are the same as 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
We can define compile-time constants of type List by adding the const keyword before the List literal:
var constantList = const [1.2.3]; // Const constantList= [1, 2, 3]
// constantList[1] = 1; // Uncomment causes an error.
Copy the code
The List type contains many List manipulation functions. See generics and collections for more information.
Set
In Dart, a Set is a Set with unique and unnecessary elements. Dart provides a Set literal and a Set type for a Set. Version tip: While the Set type has always been a core part of Dart, Set literals were introduced in Dart2.2. Here’s a simple example of creating a Set from a literal:
var halogens = {'fluorine'.'chlorine'.'bromine'.'iodine'.'astatine'};
Copy the code
⚠️ Note: Dart infer that halogens is of type Set
If you try to add a value of the wrong type to it, the parser or execution will throw an error. For more, see Type inference.
To create an empty Set, use {} preceded by 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
Is it Set or Map? The Map literal syntax is very similar to the Set literal syntax. If you forget to comment a type on {} or assign a value to an undeclared variable, Dart will create an object of type Map
Add elements to an existing Set using add() or addAll() :
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
Add const to Set literal to create a compile-time Set constant:
final constantSet = const {
'fluorine'.'chlorine'.'bromine'.'iodine'.'astatine'};// constantSet.add('helium'); // Uncommenting this causes an error
Copy the code
For more on sets, see Generic and Set
Map
In general, a Map is an object used to associate keys and values. Keys and values can be any type of object. A key can only appear once in a Map object. But value can appear more than once. Dart maps are implemented through Map literals and Map types. Here are two simple examples of using Map literals:
var gifts = {
// Key: Value
'first': 'partridge'.'second': 'turtledoves'.'fifth': 'golden rings'
};
var nobleGases = {
2: 'helium'.10: 'neon'.18: 'argon'};Copy the code
⚠️ Note: Dart will infer the type of Gifts as Map
, and nobleGases as Map
. If you try to add an error type to the map above, the parser or runtime will raise an error. For more information, read Type inference
The above Map objects can also be created using the Map constructor:
var gifts = Map(a); gifts['first'] = 'partridge';
gifts['second'] = 'turtledoves';
gifts['fifth'] = 'golden rings';
var nobleGases = Map(a); nobleGases[2] = 'helium';
nobleGases[10] = 'neon';
nobleGases[18] = 'argon';
Copy the code
⚠️ Note: why only Map() is used instead of new Map(). Because in Dart 2, the new keyword is optional. For more information, see the use of constructors
Like JavaScript, add key-value pairs to an existing Map:
var gifts = {'first': 'partridge'};
gifts['fourth'] = 'calling birds'; // Add a key-value pair
Copy the code
Like JavaScript, get a value from a Map:
var gifts = {'first': 'partridge'};
assert(gifts['first'] = ='partridge');
Copy the code
If the Map does not contain the key, then the Map returns NULL:
var gifts = {'first': 'partridge'};
assert(gifts['fifth'] = =null);
Copy the code
Use the. Length function to get the number of key-value pairs in the current Map:
var gifts = {'first': 'partridge'};
gifts['fourth'] = 'calling birds';
assert(gifts.length == 2);
Copy the code
Creates a Map type runtime constant preceded by the Map literal keyword const.
final constantMap = const {
2: 'helium'.10: 'neon'.18: 'argon'};// constantMap[2] = 'Helium'; // Uncomment causes an error.
Copy the code
For more Map content, see Generics and Maps.
Rune
In Dart, Rune is used to represent UTF-32 encoded characters in strings
- Unicode defines a global writing system encoding in which all letters, numbers, and symbols used in the system correspond to a unique numeric code.
- Because Dart strings are a series of UTF-16 encoding units, special syntax support is required to represent 32-bit Unicode values in strings
- A common way to represent Unicode code points is \uXXXX, where XXXX is a 4-digit hexadecimal value for example
- The heart character (♥) is coded as \ U2665
- To specify more or less than four hexadecimal digits, place the value in curly braces. For example, the encoding of the smiley face (😆) \u{1f600}
- StringThe class has some properties to get rune data
- The attributes codeUnitAt and codeUnit return 16-bit encoded data
- The runes property gets the Rune in the string
The following example illustrates the relationship between Rune, 16-bit code units, and 32-bit code points
main() {
var clapping = '\u{1f44f}';
print(clapping); / / 👏
print(clapping.codeUnits); / / [55357, 56399]
print(clapping.codeUnitAt(1)); / / 56399
print(clapping.runes.toList()); / / [128079]
Runes input = new Runes( '\u2665 \u{1f605} \u{1f60e} \u{1f47b} \u{1f596} \u{1f44d}');
print(input); //(9829, 32, 128517, 32, 128526, 32, 128123, 32, 128406, 32, 128077)
print(String.fromCharCodes(input)); //♥ 😅 😎 👻 🖖 😎
}
Copy the code
**⚠️ Tip: ** Be careful to use Rune as a list. Depending on the particular language, character set, and operation, this method can easily cause crashes. For more information, see How Do I Reverse a String in Dart? on Stack Overflow
Symbol
A Symbol object represents an operator or identifier declared in the Dart program. You may never need to use Symbol, but Symbol is useful when referring to an IDENTIFIER’s API by name. Because compressed code changes the name of the identifier, but not the symbol of the identifier. Get the Symbol of an identifier by adding a # sign to the literal Symbol
#radix
#bar
Copy the code
The Symbol literal is a compile-time constant