Dart Starting to In-depth Roadmap:
Dart Language — 45 minutes Quick Start (PART 1)
Dart Language — 45 minutes Quick Start (part 2)
Dart asynchronous programming in detail
Dart language asynchronous Stream details
Dart language standard flow and file manipulation
Dart Network programming
Dart crawler development experience
Dart full stack server development
Dart FFI calls C hybrid programming
Dart and Lua invocation in LuaDardo
Pay attention to me, not bad!
preface
Google’s launch of a cross-platform UI framework for Flutter has had a new impact on mobile development. Flutter is developed in Dart. Why did Flutter choose Dart as its only development language? In general, it has the following advantages
- Dart can be compiled on Ahead Of Time (AOT), that is, compiled into local code Of the platform, providing high performance.
- Dart can also be compiled on a Just-in-time (JIT) basis with fast compilation and hot loading, doubling the development cycle.
- Dart makes it easier to create smooth animations and transitions that run at 60fps. Dart does object allocation and garbage collection without locking
- Dart’s syntax combines Java and JavaScript syntax features with few uncomfortable quirks, making it easy for Java programmers to learn
Generally speaking a language or the use of AOT compilation, compilation, slow development efficiency is low, or use the JIT compiler, compiled at runtime, although can thermal overload, but the execution efficiency is low, and the Dart made a perfect balance between the two, when the development use JIT compilation, debugging, wysiwyg, development of high efficiency, when released, AOT compilation is used to compile the local code of the target platform with high execution efficiency.
Environment to prepare
Install the Dart SDK
There are three SDK versions to choose from
- Flutter
- Web
- Server
This chapter is only for learning the Dart programming syntax. You are advised to install the Server SDK and download the Windows VERSION.
Configuring environment Variables
On Windows, click Next. After the installation is complete, add the bin directory under dart-SDK to the Path environment variable. This step is a common command configuration step.
Configure the VSCode editor
To learn the Dart language, it is not recommended to download a cumbersome IDE. The official version supports VSCode editor plug-in, and it is recommended to use VSCode to learn.
Download the VSCode editor from the official website. After the installation is complete, start VSCode and search for Dart in the plug-in store to install the plug-in.
The test environment
Create a new test.dart file in VSCode and write the following code
void main(){
print("hello world!");
}
Copy the code
Hello World!
Basic grammar
Code comments
Code annotations in Dart are essentially the same as in the Java language
// Single-line comment
/* * multi-line comments */
/**
* Documentation notes */
/// Start with three slashes
/// This is a Dart specific documentation comment
Copy the code
Built-in data types
In Dart, all you can reference using variables are objects, and each object is an instance of a class. Numbers, functions, and NULL are also objects. All objects inherit from the Object class.
Note that variables that are not initialized default to null. The default value for numeric type variables is also NULL.
Num has two concrete subclasses, int and double, where int is an integer and ranges from -2^53 to 2^53. A double is a 64-bit double-precision floating-point number.
Variables and Constants
Define variables
Dart defines variables in two ways: explicitly specifying the type, as is common in statically typed languages, and explicitly specifying the type, as is common in dynamic languages, which does not specify the type and is inferred automatically by the VM.
// 1. Define variables by explicitly specifying types
String name = "Zhang";
num age = 18;
// 2. Use the keyword var without specifying the type
var address = "Shennan Avenue";
var id = 100;
/* Use var to define variables, even if the type is not explicitly specified. Once assigned, the type is fixed * so variables defined using var cannot change the data type */
var number = 19;
// The following code error cannot run, the number variable has been determined to be of type int
number = "2019";
Copy the code
If you want to change the data type of a variable dynamically, you should define the variable using dynamic or Object.
// dynamic Declares variables
dynamic var1 = "hello";
var1 = 19;
print(var1); / / 19
// Object Declares a variable
Object var2 = 20;
var2 = "Alice";
print(var2); // Alice
Copy the code
It is recommended to specify variable types explicitly when writing code to improve code readability and debugging.
Define constants
Dart also has two ways of defining constants. One uses the final keyword, as in Java, where a final variable can only be assigned once. The other is the Dart approach, which uses the const keyword definition.
// 1. Use the final keyword to define constants
final height = 10;
// 2. Use the const keyword to define constants
const pi = 3.14;
Copy the code
Note that final constants are run-time constants, while const constants are compile-time constants. That is, final constants can be defined as a variable, while const constants must be literal constants.
final time = new DateTime.now(); / / right
const time = new DateTime.now(); / / error
const list = const[1.2.3]; / / right
const list = [1.2.3]; / / error
Copy the code
Common operations of built-in types
Numeric types
/ / String int
var one = int.parse('1');
/ / the String double
var onePointOne = double.parse('1.1');
/ / int String
String oneAsStr = 1.toString();
/ / double String
String piAsStr = 3.14159.toStringAsFixed(2); // Keep two '3.14'
/ / Dart also supports integer bit operation, < <, > >, &, |
print((3 << 1) = =6); // 0011 << 1 == 0110
print((3 >> 1) = =1); // 0011 >> 1 == 0001
print((3 | 4) = =7); / / 0011 | 0100 = = 0111
Copy the code
string
It’s worth noting that the string interpolation expressions provided in Dart make string formatting extremely convenient.
Dart can use single or double quotation marks to create strings
var s1 = "hello";
var s2 = 'world';
// 2. Like Python, Dart can use triple quotes to create strings containing multiple lines
var multiLine1 = """ You can create a string of multiple lines like this;
var multiLine2 = You can also use three single quotes to create a string containing multiple lines of content.;
// 3. Like Python, you can create a primitive string by adding 'r' to the literal value of the string, so that special characters in the string are not escaped
var path = r'D:\workspace\code';
// 4.Dart supports concatenating strings using the "+" operator
var greet = "hello" + " world";
Dart provides the interpolation "${}", which can also be used to concatenate strings
var name = "Fifty";
var aStr = "hello,${name}";
print(aStr); / / hello, Cathy
// When taking only the value of a variable, you can omit the curly braces
var aStr2 = "hello,$name"; / / hello, Cathy
// When concatenating an expression, the curly braces cannot be omitted
var str1 = "link";
var str2 = "click ${str1.toUpperCase()}";
print(str2); // click LINK
// 6. Unlike Java, Dart uses "==" to compare the contents of strings
print("hello"= ="world");
Copy the code
Boolean type
Dart uses the same Boolean type as Java, and has only two values: false and true. You cannot use 0, non-0, or null, non-NULL to express false and true. Unlike Java, the default value for Boolean types is NULL
bool flags;
print(flags); // null
Copy the code
The list of
The operation of lists in Dart is similar to that of arrays in JavaScript.
// Create a list
var list = [1.2.3];
// Subscripts start at 0. Use length to access the length of a list
print(list[0]);
print(list.length);
// You can use add to add elements
list.add(5);
// Add the const keyword before the list literal to define an immutable list (compile-time constant)
var constantList = const [1.2.3];
constantList[1] = 1; / / an error
Copy the code
mapping
Also known as associative arrays, the Java equivalent of a HashMap
// 1. Create a Map using a literal
var gifts = {
'first' : 'partridge'.'second': 'turtledoves'.'fifth' : 'golden rings'
};
// 2. Use the Map constructor to create an object
var pic = new Map(a);// Add key-value pairs to the Map
pic['first'] = 'partridge';
pic['second'] = 'turtledoves';
pic['fifth'] = 'golden rings';
// 3. Obtain the Map length
print(pic.length);
// 4. Find Map
pirnt(pic["first"]);
print(pic["four"]); // Returns null if the key does not exist
Copy the code
function
In Dart, a Function (or method) is also an object, and its type is Function. This means that functions can be assigned to variables or treated as arguments to other functions.
Define a function
Dart defines functions, essentially similar to Java
String greet(String name){
return "hello,$name";
}
Copy the code
In Dart, types are optional and explicit types can be omitted, but it is still recommended to specify types explicitly.
greet(name){
return "hello,$name";
}
Copy the code
Note that functions are also objects, and all functions return values. When no return value is specified, the function returns NULL. Of course, if you force the use of void to decorate a function, then the function really does not return a value, which is another matter.
Parameters of a function
Dart supports two optional parameters
- This parameter is optional
- Location This parameter is optional
While method overloading is commonly used in Java to call different arguments to a method of the same name, Dart can do the same with optional arguments.
This parameter is optional
Let’s start with named parameters, which use curly braces to define the list of parameters
// Define a function with the argument list wrapped in curly braces
enableFlags({bool bold, bool hidden}) {
// do something
}
// Call method, use "parameter name: value" form when passing the parameter
enableFlags(hidden:true,bold:false);
Copy the code
If you set default values for parameters in the parameter list when defining a function, the parameter is optional. You can ignore the parameter and use the default value when calling the function.
// Define the add function
add({int x, int y=1.int z=0{})print(x + y + z;
}
/ / call
add(x:18); / / 19
add(x:18, y:2, z:10); / / 30
Copy the code
Note that before SDK 1.21, you can’t use the = sign to set default values for named parameters. After SDK 1.21, you can only use the = sign to set default values. Therefore, check and upgrade the SDK version.
Location This parameter is optional
Positional optional arguments use brackets to define the argument list, and the arguments in brackets are optional
// Define the add function
add(int x, [int y, int z]){
int result = x;
if(y ! =null){
result = result + y;
}
if(z ! =null){
result = result + z;
}
print(result);
}
/ / call
add(18); / / 18
add(18.12); / / 30
add(18.12.15); / / 45
Copy the code
Sets default values for the location optional parameter
// Define the add function
add(int x, [int y=0.int z=0]) {print(x + y + z); }Copy the code
Finally, you need to pay attention to the difference between named optional parameters and positional optional parameters. The parameters in the former have no relation to the sequence and do not need to be passed in sequence. The latter is related to the order in which the parameters must be passed.
Anonymous functions
Most functions have names, but we can also create nameless functions called anonymous functions, also known as lambda expressions or closures.
// Define an anonymous function and assign it to a variable func. Note that the function body must end with a semicolon in the curly bracket.
var func = (x,y){
return x + y;
};
print(func(10.11)); / / 21
Copy the code
Note that anonymous functions are basically the same as normal functions, with a list of arguments and a function body, but without the function name.
Arrow function
The arrow function in Dart is essentially the same as in JavaScript. When the function body contains only one statement, we can use the => arrow syntax for abbreviations. Note that the arrow function is just a shorthand syntax candy.
Common function
add(num x, num y){
return x + y;
}
print(add(18.12)); / / 30
Copy the code
Arrow function
// Exactly equivalent to the ordinary function above
add(num x, num y) => x + y;
print(add(18.12)); / / 30
Copy the code
The arrow function omits the expression of curly braces. The arrow is followed by an expression, and the return value of the function is the value of that expression. In addition, arrow functions can also be combined with anonymous functions to form anonymous arrow functions.
var func = (num x, num y) => x + y;
Copy the code
The operator
Operators in the Dart language are almost identical to those in Java.
Arithmetic operator
+, -, *, /, % the same as the Java language
Dart also provides the divisor operator ~/, which returns the result of division as a whole.
Type determination operator
Here are the type-dependent operators Dart adds.
The operator | explain |
---|---|
as |
For type conversion |
is |
Returns True if the object is of the specified type |
is! |
Returns True if the object is not of the specified type |
Obj is T is true if obj implements T’s interface. Similar to Instanceof in Java.
Dart uses the AS operator to convert an object to a specific type. If it cannot convert, an exception will be thrown. Therefore, it is best to use the IS operator to check before converting.
// Convert p to Person
(p as Person).name = 'Bruce';
Copy the code
Conditional expression
Condition is also supported in Dart. expr1 : expr2
Dart also adds a nonnull condition identifier?? expr1 ?? Expr2 If the value of expr1 is not null, the value of expr1 is returned. Otherwise, the expression expr2 is executed and the result is returned.
var str1 = "Hello";
var str2 = "world";
var result = str1 ?? str2.toUpperCase();
Copy the code
Cascade operator
We typically call methods on objects using the. Operator, which is also supported in Dart, but Dart adds a cascade operator as well.. And is represented by two dots.
Cascade operators can continuously call multiple methods and access member variables on the same object. Use it to avoid creating temporary variables and write smoother code.
If the class Person has three methods, setName, setAge, and save, it can be called as follows
newPerson().. setName("Bob").. setAge(20).. save();Copy the code
Using the cascade operator to call a method, you can continuously stream calls to other methods of the object without the method returning the object itself.
Conditional member accessors
In Java, it’s easy to get annoying null-pointer errors, so you need to make a non-null determination of an object before calling a method, which makes your code long, unreadable, and untidy. Dart has invented a new operator to handle such cases.
Conditional member accessors? ., which is similar to., except that the object to the left of the operator cannot be null, otherwise null is returned, or the object itself is returned if the object is not null.
// list1 defaults to null
List list1;
print(list1? .length);// null
List list2 = [];
print(list2? .length);/ / 0
Copy the code
Branches and loops
Conditional branch
Conditional branching in Dart is essentially the same as in Java
If conditional branch
if(i < 0) {print('i < 0');
}else if(i == 0) {print('i = 0');
} else {
print('i > 0');
}
Copy the code
Switch conditional branch
// You can use integers, strings, enumerated types, and compile-time constants in switch cases
String command = 'OPEN';
switch (command) {
case 'CLOSED':
break;
case 'OPEN':
break;
default:
print('Default');
}
Copy the code
Looping statements
The basic cycle
The basic loop statement in Dart is the same as in Java
/ / a for loop
for(int i = 0; i < 9; i++) {
print(i);
}
/ / while loop
while(true) {//do something
}
/ / the do while loop
do{
//do something
} while(true);
Copy the code
Special circulation
var myList = ['Java'.'JavaScript'.'Dart'];
// for... in... Loop, similar to the enhanced for in Java
for (var it in myList ){
print(it);
}
// forEach loop. The argument is a Function object, where an anonymous Function is passed in
myList.forEach((var it){
print(it);
});
// You can use the shorthand for the anonymous arrow function
myList.forEach((it) => print(it));
Copy the code
Use a loop to traverse the Map
var myMap = {
'zhangsan':'201901'.'lisi':'201902'.'wangwu':'201902'
};
// forEach traverses the Map
myMap.forEach((k, v) => print("$k : $v"));
// get the value by key. Keys returns the set of all keys in the Map
for(var k in myMap.keys){
print("$k : ${myMap[k]}");
}
Copy the code
Next Dart Language — a 45-minute Quick Start (part 2)
My personal blog
GitHub
Dart Language – 45 minutes quick start
Video course
Related video courses posted by bloggers
Dart Programming Guide for Flutter full stack development
Guide to the full stack development of Flutter
Follow my official account: The path of programming from 0 to 1