Preface
Recently, I am learning to do flutter mobile development. Compared with React-Native development, using the language Dart is necessary to develop, which leads to a heavier learning burden. So I will summarize the syntax and use of the Dart language.
The following content is referenced fromDart official documentation
1. Installation and use
dart is an object-oriented programming language developed by Google. Mainly used in mobile terminals,flutter
use. dart2 is a stable version used at this stage
1.1 Installation
Because most of learning dart is to write flutter, it is recommended to download flutter directly. The downloaded flutter will have the SDK of dart.
Flutter is recommended to go to the official websitedownload. After the download is completed, the SDK of dart is hereUnzip directory\bin\cache\dart-sdk
Down.
1.2 Use in vscode
For convenience, we can set the SDK of dart in the environment variable andUnzip directory\bin\cache\dart-sdk\bin
Set the full path of the . Enter dart in cmd . If there is a response, it means that the setting is successful.
Then there is how to use dart in vscode. In order to use dart, I need to download two pluginsDart
andCode Runner
, create a file after downloading, enter the following code:
// The code in dart needs to be put into the main method to execute main(){ print('Hello World'); }
Then right-clickRun Code
, if the console prints out successfullyHello World
Prove that we are already able to use dart in vscode.
2. Type declaration
2.1 Variable declaration
There are many keywords that declare variables in dart. You can use variable declarations that can accept any type of value (similar to JavaScript), or you can use variable declarations that can only accept fixed type of value (similar to JAVA).
2.1.1 var
Similar to JavaScriptvar
, it can receive any type of variable, but the biggest difference is in dartvar
Once a variable is assigned a value when declared (except as null, because all values are null at initialization), the type will be determined and its type cannot be changed, such as:
var t = "hi world"; // The following code will report an error in dart because the type of variable t has been determined as String // Once the type is determined, its type cannot be changed. t = 1000;
💡 For front-end personnel, it is actually considered to be the automatic inference type function of TypeScript.
But if there is no direct assignment at the beginning, but only definition, then the type of the variable will bedynamic
Type, that is, the usage is the same as the declared variables in JavaScript.
var t; t = "hi world"; // The following code will not report errors in dart t = 1000;
2.1.2 const and final
If you have never intended to change a variable, usefinal
orconst
,novar
, is not a separate type declaration (type declaration can also change the value. When defining variables with type declarations, you can directly prefix themconst
orfinal
Keywords make it a constant, but we generally recommend omitting type declarations).
useconst
andfinal
The declared variables can only be set once, the difference between the two is:
const
A constant is a compile-time constant (that is, it must be a constant that is completely fixed when the program is compiled).final
Constants not only haveconst
The most important thing about the compile-time constant is that it is a run-time constant.final
It is lazy initialized, that is, it will not be initialized on the first use.
// You can omit the statement of String type final str = "hi world"; final String sstr = "hi world"; const str1 = "hi world"; const String sstr1 = "hi world"; // Runtime constants will be assigned at runtime // Get the current time, because it is obtained dynamically, it cannot be declared through const final t = new (); // OK const t1 = new (); // Error
Notice:
Although final is a runtime constant, the first time it is assigned must be assigned at the time of definition.
final a; // Error a = 1;
The instance variable can be final, but not const. (Instance variable is defined at the object level. It can be accessed by any method in the class or methods in other classes, but cannot be accessed by static methods)
class A {} main() { final a = new A(); // OK const b = new A(); // Error }
The const keyword does not just declare constant variables. It can also be used to create constant values, as well as to declare constructors that create constant values. Any variable can be assigned a constant value.
var foo = const []; final bar = const []; // Const can be omitted from the initialization expression declared by the const const baz = []; // Equivalent to `const []` => const bar = const []; // Cannot change the value of the const variable baz = [42]; // Error: Constant variables can't be assigned a value. // Can change the value of a non-final non-const variable even if it once had a const value foo = [1, 2, 3]; // Was const []
Some classes provide constant constructors. To create compile-time constants using a constant constructor, place the const keyword before the constructor name:
class Person{ const Person(); } var p = const Person();
2.1.3 dynamic and Object
-
Object
is the base class of all objects, that is, all types areObject
Subclasses of (includingFunction
andNull
), so any type of data can be assigned toObject
The object declared. -
dynamic
Yes withint
For such type keywords, variables declared by changing the type can also be assigned to any object.
💡 dynamic
andObject
The same is that the variables they declare can change the assignment type later (similar to using JavaScript or TypeScriptany
type).
dynamic t; Object x; t = "hi world"; x = 'Hello Object'; // There is no problem with the following code t = 1000; x = 1000;
dynamic
andObject
The difference is,dynamic
The declared object compiler will provide all possible combinations (that is, it is equivalent to a complete JavaScript variable), andObject
The declared object can only use the properties and methods of the Object class, otherwise the compiler will report an error.
dynamic a; Object b; main() { a = ""; b = ""; printLengths(); } printLengths() { // no warning print(); // warning: // The getter 'length' is not defined for the class 'Object' print(); }
2.1.4 Default value
The initial value of an uninitialized variable is null. Even variables with numeric types are null initially because everything in dart is an object.
int lineCount; assert(lineCount == null);
Notice:In production environment,assert()
The call is ignored. In the development environmentassert(condition)
A exception is thrown when the condition condition is not true.
2.2 Data Type
What we need to be clear is that all types of values in dart are objects, so the basic type declaration commonly used in other languages is essentially a type declaration of a class in dart.
2.2.1 Number
There are three types of Number that can be used in total:
- num
- int
- double
Dart's numbers come in two forms:
int: Depending on the platform, the integer value is not greater than 64 bits. On a Dart VM, the value can be from-263
arrive263 - 1
. Dart compiled into JavaScript uses JavaScript code to allow values from-253
arrive253 - 1
。
An integer is a number without a decimal point. Here are some examples of defining the integer surface quantity:
int x = 1; int hex = 0xDEADBEEF;
int type specifies traditional(<<, >>) and (&), or (|)
bit operator. For example:
assert((3 << 1) == 6); // 0011 << 1 == 0110 assert((3 >> 1) == 1); // 0011 >> 1 == 0001 assert((3 | 4) == 7); // 0011 | 0100 == 0111
double: 64-bit (double precision) floating point number, specified by the IEEE 754 standard.
If a number contains a decimal, it is a double number. Here are some examples that define double literals:
double y = 1.1; double exponents = 1.42e5;
Note:int and double are both subtypes of num . num type includes basic operators, such as+, -, / and *
, can also be found in itabs(), ceil() and floor()
etc. (bit operator, such as>>
, defined in the int class) If num and its subtypes have nothing to look for, thendart:math library
There may be.
Here's how to convert a string to a number and vice versa:
// String -> int var one = ('1'); assert(one == 1); // String -> double var onePointOne = ('1.1'); assert(onePointOne == 1.1); // int -> String String oneAsString = (); assert(oneAsString == '1'); // double -> String String piAsString = 3.(2); assert(piAsString == '3.14');
2.2.2 String
The dart string is a sequence of UTF-16 encoding units. You can create a string using single or double quotes:
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.";
Available${expression}
WillValue of expressionPut it into a string. If the expression isAn identifier, you can skip{}
. In order to obtain the string corresponding to the object, dart will automatically call the object's toString() 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. ' + '${()} is very handy!' == 'That deserves all caps. ' + 'STRING INTERPOLATION is very handy!');
Notice:== Check whether the two objects are equal. If two strings contain code units of the same sequence, they are equivalent, similar to JavaScript.
AvailableAdjacent string literals (can also be regarded as using spaces)or+Operator concatenation string:
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.');
For a method to create a multi-line string:
- use
\n
Used as a newline. - Use triple quotes with single or double quotes.
var s = 'a \n multi-line string' var s1 = ''' You can create multi-line strings like this one. '''; var s2 = """This is also a multi-line string.""";
If you don't want to escape characters, you can user
Prefix to create aOriginal string:
var s = r'In a raw string, not even \n gets special treatment.'; // In a raw string, not even \n gets special treatment.
Note that string literals are compile-time constants. As long as any interpolated expression is a compile-time constant, the calculation result is null or a numeric, string or boolean.
// 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'; // Error /* The first three errors are because the variable declared using var can be changed afterwards and does not conform to the constant definition. The second one is because it does not conform to the type required by the constant, that is, it does not conform to null or numeric, string or boolean. Even if you use the toString() method, it will report an error, which does not conform to the definition of compile-time constants unless you use final */
2.2.3 Boolean
To represent boolean values, dart has a type named bool. Only two objects have bool types: boolean literal true and false, both compile-time constants.
The type safety of dart means it cannot be usedif(non-booleanvalue)
orassert(non-booleanvalue)
Code like that. Instead, explicitly check the values, such as:
// Check for an empty string. var fullName = ''; assert(); // 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();
2.2.4 List
As long as the basic usage of List, Set, Map, etc. are shown in the use of common libraries for dart
Lst API Documentation
Perhaps the most common collection in almost any programming language is arrays or ordered object groups. In dart, arrays are list objects, so most people call them lists.
dart list literals look like JavaScript array literals. Here is a simple list of darts:
var list = [1, 2, 3];
Notice:The above code analyzer infers that the list hasList<int>
type. If you try to add a non-integer object to this list, an error will be raised by the analyzer or runtime.
You can get the length of the list and reference the list element, just like in JavaScript:
var list = [1, 2, 3]; assert( == 3); assert(list[1] == 2); list[1] = 1; assert(list[1] == 1);
To create a compile-time constant list (cannot change the value afterward), you need to add const before the list literal (or use the const declaration variable directly):
var constantList = const [1, 2, 3]; // OR const constantList = [1, 2, 3]; // constantList[1] = 1; // Uncommenting this causes an error. // There will be no errors reported during compilation, but an exception will be thrown during runtime.
There are many ways to facilitate list operation. I will not talk about it here, but will be explained in detail later.
2.2.5 Set
Set API Documentation
The collection in dart is a unique collection of unordered items. Because the set is unordered, the items of the set cannot be obtained through the index (position).
var ingredients = Set(); (['gold', 'titanium', 'xenon']); assert( == 3); // Adding a duplicate item has no effect. ('gold'); assert( == 3); // Remove an item from a set. ('gold'); assert( == 2);
usecontains()
andcontainsAll()
To check whether there are one or more objects in the collection:
var ingredients = Set(); (['gold', 'titanium', 'xenon']); // Check whether an item is in the set. assert(('titanium')); // Check whether all the items are in the set. assert((['titanium', 'xenon']));
An intersection is a set whose items are in two other sets:
var ingredients = Set(); (['gold', 'titanium', 'xenon']); // Create the intersection of two sets. var nobleGases = (['xenon', 'argon']); var intersection = (nobleGases); assert( == 1); assert(('xenon'));
2.2.6 Map
Map API Documentation
Typically, map is an object that associates keys and values.Both keys and values can be objects of any type. Each key only appears once, but you can use the same value multiple times. dart's support for maps is provided through map literals and map types. (It can be seen as an object that is mixed with JavaScript object literal writing and JAVA's HashMap key value)
var gifts = { // Key: Value 'first': 'partridge', 'second': 'turtledoves', 'fifth': 'golden rings' }; var nobleGases = { 2: 'helium', 10: 'neon', 18: 'argon', };
Notice:
In the above code, the parser infers that the type of gifts isMap<String, String>
, the type of nobleGases isMap<int, String>
. If you try to add a value of the error type to map, the analyzer or runtime will throw an error.
There is a difference between maps in dart and objects in JavaScript. Keys can be of any data type, and quotes cannot be omitted if they are of String type, because in dart this will parse them into a variable.
const a = '1'; var map1 = { true: '123', a: '2', // A without quotes will be parsed as '1' b: '2', // An error is reported, no b variable 'a': '2' };
Similarly, when getting the value through the map key, you cannot use the common JavaScriptpoint(.)
Operators, only[]
operator,point(.)
Operators can only be used to obtain properties or methods of objects generated by classes in dart (because the arguments generated by map only look the same as those in JavaScript, but there is actually a big difference).
You can also use the Map constructor to create objects:
var gifts = new Map(); gifts['first'] = 'partridge'; gifts['second'] = 'turtledoves'; gifts['fifth'] = 'golden rings'; var nobleGases = new Map(); nobleGases[2] = 'helium'; nobleGases[10] = 'neon'; nobleGases[18] = 'argon';
Adding values and retrieving values are done just like in JavaScript, the difference is:
If the key to be retrieved is no longer in the map, a null will be returned:
var gifts = {'first': 'partridge'}; assert(gifts['fifth'] == null);
Available.length
Get the number of elements in the map:
var gifts = {'first': 'partridge'}; gifts['fourth'] = 'calling birds'; assert( == 2);
To create a compile-time constant map, you need to prefix the literal of the mapconst
Keywords (or variables declared directly with const):
var constantMap = const { 2: 'helium', 10: 'neon', 18: 'argon', }; // OR const constantMap = { 2: 'helium', 10: 'neon', 18: 'argon', }; // constantMap[2] = 'Helium'; // Uncommenting this causes an error. // There will be no errors reported during compilation, but an exception will be thrown during runtime.
2.2.7 Runes (character)
In dart, characters are UTF-32 encoded points of the string.
Unicode defines a unique numerical value for every letter, number, and symbol used in all writing systems in the world. Because the dart string is a sequence of UTF-16 code units, it requires special syntax to represent 32-bit Unicode values in the string.
The common method to represent Unicode code points is\uXXXX
, where XXXX is a hexadecimal value of 4 digits. For example, the heart-shaped character (♥) is encoded as\u2665
. To specify a 4-digit hexadecimal number greater than or less, place the value in curly braces. For example, the encoding of smiley expressions (😆)\u{1f600}
。
The String class has several properties that can be used to obtain runes information. The codeUnitAt and codeUnit properties return 16-bit code units. Use the character attribute to get the characters of the string.
The following example illustrates the relationship between a character, a 16-bit code unit, and a 32-bit code point:
main() { var clapping = '\u{1f600}'; print(clapping); print(); print(()); Runes input = new Runes( '\u2665 \u{1f605} \u{1f60e} \u{1f47b} \u{1f596} \u{1f44d}'); print(new (input)); } //The operation effect is as follows😀 [55357, 56832] [128512] ♥ 😅 😎 👻 🖖 👍 Process finished with exit code 0
Notice:Be careful when using list operations to operate runes. This approach is prone to errors depending on the specific language, character set, and operations. For more information, seeHow to reverse a string in Dart?
2.2.8 Symbols (symbols)
A symbolic object represents an operator or identifier declared in the dart program. Generally speaking, symbols may never be required, but for APIs that refer to identifiers by name, they are very important because the reduction changes the identifier name rather than the identifier symbol.
To get the symbol of the identifier, use the symbol text, the symbol text is only#
, followed by the identifier:
#radix #bar
Notice:Symbol constants are compile-time constants.
2.2.9 Enumeration Type
Enumeration types can be regarded as an extension of dart to class.
useenum
Keyword declares an enum type:
enum Color { red, green, blue }
Each value in the enum has an index getter, which returnsenum
Declare the position of the value starting from 0. For example, the first value has index 0 and the second value has index 1.
assert( == 0); assert( == 1); assert( == 2);
useenum
ofvalues
Constant to get a list of all values in the enum.
List<Color> colors = ; assert(colors[2] == );
Can be used in switch statementsenum
, if the switch case is not processedenum
All values of , a warning message will be reported:
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); // '' }
Enumeration types have the following limitations:
- Cannot subclass, mix, or implement enumeration.
- An enum cannot be explicitly instantiated.
The above is the detailed explanation of the variable declaration and data type instance of Dart syntax. For more information about Dart variable declaration data types, please pay attention to my other related articles!