The Dart basis
To learn a new language, we can use the analogy of our existing familiar language. For example, we are very familiar with Java, so the rest of us need to master Dart syntax, which is different from Java. The rest of us need to write more and get familiar with it.
International convention, use Dart to do one: “Hello, World!”
void main() {
print('Hello, World! ');
}
Copy the code
Dart to run the Dart code, run Dart xxx. Dart. You need to configure environment variables in the Dart command by adding ${FLUTTER_SDK}/bin/cache/dart-sdk/bin to the PATH variable. (Dart Black Window configuration)
variable
A variable is a reference, and the value of an uninitialized variable is NULL.
Object name1 = 'Daniels';
var name2 = 'Daniels';
dynamic name3 = 'Daniels';
print('$name1 $name2 $name3');
// A variable is a reference. The above name1, name2, and name3 variables all refer to a String containing "Daniels".
Copy the code
Variables declared with Object, var, and dynamic can be assigned to any type of value, but the underlying principle is very different.
1. Object: Like Java, Object is the base class of all classes. Variables declared by Object can be of any type. (Even numbers, methods, and NULL are objects in Dart, such as ints.)
Object a = 1;
a = "a";
Copy the code
Var: The declared variable determines its type at the moment of assignment. (Type inference)
//a has been set to num, and cannot be assigned a string, otherwise compilation error
var a = 1;
a = "a";
/ / right
var b;
b = 1;
b = "a";
Copy the code
Dynamic: The actual type is determined not at compile time, but at run time. Dynamic declares variables that behave and use the same as Object, but the key is different at runtime.
Variables that are not initialized automatically get a default value of NULL (variables of type number are null even if they are not initialized).
Int a = 1; int a = 1;
For local variables, the Dart code style recommends using var instead of a specific type to define local variables.
The final and const
If you do not intend to change a variable, you can use final and const, which can replace any type, can only be initialized at declaration time, and cannot be changed.
const a = 1;
final b = 1;
final int c = 1;
const int d = 1;
Copy the code
Final is indistinct in use from const, but final is a runtime constant, and const is a compiler constant whose value is determined at compile time, which makes code run more efficiently.
// Correct, already determined value
const a = 1;
const b = a + 1;
// Error,final cannot determine a value at compile time, so const cannot determine a value
final a = 1;
const c = a + 1;
Copy the code
Class variables can be final but not const. If const is in a class, we need to define it as a static const static constant
! [const member]
class Demo{
static const i = 123; //true
const j = 123; //false
}
Copy the code
Built-in types
Unlike Java’s eight built-in basic data types, Dart supports the following types:
- numbers
- strings
- booleans
- Lists (also known as listsarrays)
- maps
- Runes (used to represent Unicode characters in strings)
- symbols
Numbers
Num is the parent class of the number type, with two subclasses int and double.
Strings
The Dart string is a sequence of utF-16 encoded characters. Strings can be created using either single or double quotation marks, which can be nested, or escaped using \. Variables and expressions can also be referenced in strings.
var name = 'lance';
// If a simple identifier is inserted that is not followed by more alphanumeric text, {} should be omitted.
var a = "my name is $name!";
var b = "my name is ${name.toUpperCase()}!";
Copy the code
As in Java, we can use the + operator to concatenate strings, or we can group strings together to achieve the same function:
var a = "my name is " "lance";
Copy the code
You can create a multi-line string object with three 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
Providing an R prefix creates a “raw” string
print(R "Newline: \n"); // Newline: \n r: no need to escape
print("Newline: \\n"); // Newline: \n
Copy the code
Booleans (Boolean value)
Dart has a type named bool. Only two objects are Boolean: true and false. This is not that different from Java.
We have Lists.
Probably the most common collection in almost any programming language is an array or an ordered group of objects. In Dart, arrays are List objects. Iterating over a List is also Java.
var list = [1.2.3];
// The subscript index of Lists starts from 0 and the first element is 0. List. length-1 is the index of the last element
print(list[list.length- 1]);
// Modify the element
list[0] = 2;
// Use new (actually new can be omitted)
var list = new List(1);
list[0] = 2;
// Add the const keyword before the list literal to define an immutable list object (compile-time constant)
var list = const [1.2.3];
i.add(2); ///Error, list is immutable
Copy the code
Maps
Map: Objects associated with key-value pairs. Keys and values can be objects of any type. Each key appears only once, while a value can appear multiple times.
// Use {} to separate key and value pairs with commas
var companys = {'a': Alibaba.'t': 'company'.'b': "Baidu"};
var companys2 = new Map(a); companys2['a'] = Alibaba;
companys2['t'] = 'company';
companys2['b'] = "Baidu";
// Add elements
companys['j'] = 'jingdong';
// Get and modify elements
var c = companys['c']; ///Returns null for no corresponding key
companys['a'] = 'alibaba';
Copy the code
As with List, we can define a map that is constant at compile time by adding the const keyword before the map literal
Runes (used to represent Unicode characters in strings)
If you need to obtain Unicode encodings for special characters, or if you need to convert 32-bit Unicode encodings to strings, you can use the Runes class.
The common way Dart expresses Unicode code points is \uXXXX, where XXXX is a four-digit hexadecimal value. To specify more or less than four hexadecimal digits, place the value in braces.
var clapping = '\u{1f44f}'; ///5 hexadecimal numbers need to use {}
print(clapping);/ / 👏
// Get a 16-bit code unit
print(clapping.codeUnits); / / [55357, 56399]
// Get the Unicode code
print(clapping.runes.toList()); / / [128079]
//fromCharCode creates a string from the character code
print( String.fromCharCode(128079));
print( String.fromCharCodes(clapping.runes));
print( String.fromCharCodes([55357.56399]));
print( String.fromCharCode(0x1f44f));
Runes input = new Runes(
'\u2665 \u{1f605} \u{1f60e} \u{1f47b} \u{1f596} \u{1f44d}');
print(String.fromCharCodes(input));
Copy the code
In fact Runes and the next Symbols may never be used in Flutter development.
Symbols
Operator identifier, which can be thought of as a macro in C. Represents a constant at compile time
var i = #A; / / constant
main() {
print(i);
switch(i){
case #A:
print("A");
break;
case #B:
print("B");
break;
}
var b = new Symbol("b");
print(#b == b); ///true
}
Copy the code
The operator
There’s nothing more to say about the common operators, but let’s focus on what Java doesn’t have.
Type determination operator
As, is, and is! Operators are operators that determine the type of an object at runtime
The operator | explain |
---|---|
as |
Type conversion |
is |
Returns true if the object is of the specified type |
is! |
Returns false if the object is of the specified type |
The AS operator converts an object to a specific type, but throws an exception if the conversion cannot be completed
Is is the same as Instanceof in Java
The assignment operator
=, +=, \=, *= needless to say, there is another?? The = operator is used to specify the value of a variable whose value is null
b ?? = value;// If b is null, value is assigned to b;
// If not null, the value of b remains unchanged
Copy the code
Conditional expression
Dart has two special operators that can be used instead of if-else statements:
-
condition ? expr1 : expr2
If condition is true, exPR1 is executed (and the result of execution is returned); Otherwise, exPR2 is executed and the result is returned.
-
expr1 ?? expr2
If expr1 is not null, return its value; Otherwise, exPR2 is executed and the result is returned.
Cascade operators
Cascade operators (..) Multiple functions can be called consecutively on the same object and member variables can be accessed. Using the cascade operator avoids creating temporary variables, and the written code looks smoother:
//StringBuffer write is the Java append
var sb = new StringBuffer(a); sb.. write('foo').. write('bar');
Copy the code
Security operator
Dart provides? . Operator. The operation object on the left returns NULL if null
String sb;
/ / null pointer
print(sb.length);
print(sb? .length);Copy the code
methods
int add(int i,int j) {
return i + j;
}
// You can also ignore the type (not recommended)
add( i, j) {
return i + j;
}
// For methods that have only one expression, you can choose to use the abbreviation syntax:
add(i, j) => i + j;
// in arrows (=>) and semicolons (;) Only one expression can be used between
Copy the code
First-class method object
Dart is a true object-oriented language where methods are also objects and have a type Function. This means that methods can be assigned to variables or treated as arguments to other methods. You can call another method as an argument
var list = [1.2.3];
// Pass the print method as an argument to forEach
list.forEach(print);
// A method can be assigned to a variable of type Funcation
var p = print;
list.forEach(p);
Copy the code
In Java, you might need to specify an interface, such as onClickListener for a View, if you want to be able to notify the caller or elsewhere about the execution of a method. In Dart, you can specify a callback method directly to the calling method, which executes the callback at the appropriate time.
void setListener(Function listener){
listener("Success");
}
/ / or
void setListener(void listener(String result)){
listener("Success");
}
// There are two ways. The first way is that the caller is not sure what the return value and parameters of the callback function are
// The second one needs to write such a long paragraph.
A method that returns voide and takes a String is defined as a type.
typedef void Listener(StringThe result);void setListener(Listener listener){
listener("Success");
}
Copy the code
Methods can have two types of parameters: required and optional. The required parameters need to precede the parameter list, followed by the definition of optional parameters.
Optional named parameter
Put the method arguments in {} to make them optional named arguments
int add({int i, int j}) {
if(i == null || j == null) {return 0;
}
return i + j;
}
Copy the code
When calling a method, you can use the form paramName: value to specify named parameters. Such as:
// No required parameters
add()
// Select pass parameters
add(i:1)
// Position does not matter
add(i:1, j:2)
add(j:1, i:2)
Copy the code
Optional position parameter
The method arguments become optional positional arguments by placing them in [], and the values are passed in the order of their positions
int add([int i, int j]) {
if(i == null || j == null) {return 0;
}
return i + j;
}
// 1 is assigned to I
add(1);
// Assign values in order
add(1.2);
Copy the code
Default Parameter Value
When defining methods, optional arguments can use = to define default values for optional arguments.
int add([int i = 1, int j = 2]) => i + j;
int add({int i = 1, int j = 2}) => i + j;
Copy the code
Anonymous methods
Methods without names are called anonymous methods and can also be called lambda or closure closures. Anonymous methods are declared as follows:
([Type] param1,...). { codeBlock; };Copy the code
Such as:
var list = ['apples'.'oranges'.'grapes'.'bananas'.'plums'];
list.forEach((i) {
print(list[i]);
});
Copy the code
abnormal
Unlike Java, all Dart exceptions are non-checked exceptions. Methods do not necessarily declare the exceptions they throw, and do not require you to catch any.
Dart provides the Exception and Error types, as well as several subtypes. You can also define your own exception types. However, the Dart code can throw any non-NULL object as an Exception, not just an object that implements an Exception or Error.
throw new Exception('This is an exception.');
throw 'This is an exception.';
throw 123;
Copy the code
Unlike Java, Dart catches exceptions using catch statements, but Dart does not specify the type of exception. The syntax is as follows:
try {
throw 123;
} on int catch(e){
// Use on to catch exception objects of type int
} catch(e,s){
The catch() function can take one or two arguments. The first argument is the exception object thrown and the second is the StackTrace.
rethrow; // Use the 'rethrow' keyword to rethrow the caught exception
} finally{}Copy the code
Use Dart to bubble sort any int array from smallest to largest.
void main() { // Bubble sort. ^ Ask if you don't understand
List<int> array = [1.12.7.35.10];
for (var i = 0; i < array.length - 1; i++) {
for (var j = 0; j < array.length - 1 - i; j++) {
if (array[j] > array[j + 1]) {
array[j] = array[j] ^ array[j + 1];
array[j + 1] = array[j] ^ array[j + 1];
array[j] = array[j] ^ array[j + 1]; }}}Copy the code