• I. Introduction to Dart
  • Ii. Dart Foundation
    • 1. Several important concepts
    • Dart keyword
    • 3. Entry function
    • 4. Code comments
  • Three, variables,
    • 1. Define variables
    • 2. Dynamically change variable types
    • 3. Define constants
  • 4. Built-in types
    • 1. Number
    • 2. String
    • 3. Boolean
    • 4. List
    • 5. Set
    • 6. Map
  • 5. Operators
    • 1. Arithmetic operators
    • 2. Type judgment operator
    • 3. Assignment operators
    • 4. Logical operators
    • 5. Bit operators
    • Conditional expressions
    • 7. Cascade operators
  • 6. Process control statements
    • 1. If-else branch
    • 2. The switch-case statement
    • 3. The for loop
    • 4. While and do while loops
    • 5. Break and continue
    • 6. Other loops
    • 7. An assert statement
  • 7. Exception handling
    • 1. Throw an exception
    • 2. try… catch… Finally catch exceptions
  • Eight, summary

I. Introduction to Dart

In my previous article, “Advance to Flutter (II) — Building a Flutter Development Environment”, I introduced how to build a Flutter development environment. Now you can use the computer that has built the environment to learn the Flutter development language — the Everything object Dart language.

Dart is a breeze for readers who have mastered C, C++, Java, or Javascript.

Let’s start by introducing the Dart language.

Dart, like Flutter, was developed by Google. Why did Goolgle choose Dart as the development language for Flutter? In summary, using Dart development has the following advantages:

  • Dart can be compiled on AOT (Ahead Of Time) or JIT (Just In Time). JIT based compilation allows hot loading, doubling the development cycle (Flutter has subsecond stateful thermal overload).
  • Dart makes it easier to create smooth animations and transitions that run at 60fps. Dart does object allocation and garbage collection without locking.
  • Dart is an object-oriented programming language that combines Java and JavaScript syntax features that will be familiar to many existing developers. If you already know C++, C#, or Java, getting started with Dart will be quick.
  • Dart can be compiled to ARM and x86 code, so Dart mobile applications can run natively on iOS, Android, and later. Dart can be converted to JavaScript for Web applications.

Generally speaking, a language either uses AOT compilation, which is slow to compile and inefficient to develop; Dart strikes a perfect balance between JIT compilation, compilation at run time, hot reloading, but inefficient execution. When the development of JIT compilation, debugging fast, WHAT you see is what you get, high development efficiency; When released, AOT is used to compile into native code for the target platform, which is highly efficient.

Ii. Dart Foundation

1. Several important concepts

Here are some facts and concepts to be aware of as you learn the Dart language:

  • Dart statements are semicolons;At the end of the.
  • Anything stored in a variable is an object, and all objects are instances of a corresponding class. Whether it’s numbers, functions andnullThey’re all objects. All objects inherit from the Object class.
  • Although Dart is strongly typed, Dart can infer types, so type annotations are optional. To specify that no type is required, use the special type Dynamic.
  • Dart supports generics, such asList <int>(integer list) orList <dynamic>(List of objects of any type).
  • Dart supports top-level functions, such asmain()Again, functions are bound to classes or objects (static and instance functions, respectively). And support for creating functions (nested or local) within functions.
  • Dart supports top-level variables, which are bound to classes or objects (static and instance variables). Instance variables are sometimes called fields or properties.
  • Unlike Java, Dart does not have keywordspublicprotectedprivate. If the identifier is underlined_First, it is private relative to the library.
  • Identifiers are letters or underscores_Beginning followed by any combination of letters and numbers.

Dart keyword

The Dart language keywords are as follows:

Avoid using these words as identifiers when using Dart.

3. Entry function

Dart has two main entry functions:

main(){
  print('Hello Dart! ');
}

// Void denotes no return value
void main(){
  print('Hello Flutter! ');
}
Copy the code

4. Code comments

Dart supports single-line, multi-line, and document comments:

  1. Single-line comments: single-line comment//Start. All in//And the end of the line change is ignored by the compiler.
  2. Multiline comment: multi-line comments/ *Began to* /At the end. All in/ ** /Is ignored by the compiler (document comments are not ignored). Multi-line comments can be nested.
  3. Documentation comments: A document comment can be a multi-line comment or a single-line comment///or/ * *Start. Use on consecutive lines///Has the same effect as a multi-line document comment.
// Single-line comment

/* * multi-line comments */ 

/// Documentation comments

/支那* Documentation notes */
Copy the code

Three, variables,

1. Define variables

Dart has two ways of defining variables. One is to specify the type of a variable, as is common in statically typed languages. The other is the common approach for dynamic languages, where no type is specified and Dart automatically determines the type. I recommend specifying variable types when writing code to improve code readability and debugging.

// Specify the variable type:
String name = 'ImportV';

// Use the keyword var without specifying the type of the variable:
var name = 'ImportV';
Copy the code

The default value for uninitialized variables is NULL. The default value is null even if the variable is a numeric type, because everything is an object in Dart, and numeric types are no exception.

int a;
print(a);  // Output value is null
Copy the code

2. Dynamically change variable types

If you want to change the data type of a variable dynamically, you should define the variable using dynamic or Object:

dynamic a = 'Dart';  // You can also use Object a = 'Dart';
a = 2021;
print(a);  // The output is 2021
Copy the code

3. Define constants

Dart also has two ways of defining constants, either using the final keyword or using the const keyword. It is important to 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.

final a = DateTime.now();
print(a);  // Outputs the current time

const a = DateTime.now();
print(a);  / / an error
Copy the code

4. Built-in types

The Dart language supports the following built-in types:

1. Number

// int must be an integer:
int a = 123;

// Starting with Dart 2.0, double can be either a float or an integer:
double b = 12.34;
double c = 6;    // Double c = 6.0
Copy the code

2. String

// Use single or double quotation marks to define strings:
String s1 = 'Hello Dart! '
String s2 = "Hello Flutter!"

// When a string is in quotes:
String s3 = 'I\'m ImportV! '
string s4 = "I'm ImportV!"

// Create a multi-line string object with three consecutive single or double quotation marks:
String s5 = '''
Hello Dart! 
Hello Flutter! 
Hello ImportV!
''';
// Using the r prefix, you can create "raw" strings:
String s6 = r'Hello Dart \n Hello Flutter! '

// String -> int:
int a = int.parse('123');

// String -> double:
double b = double.parse('12.34');

// int -> String:
String str1 = 123.toString();

// double -> String:
String str2 = 12.3456.toStringAsFixed(2);  // Parentheses are the number of decimal places to be reserved

// String concatenation, with "+" concatenation, literal strings can also be written directly together:
String s1 = 'Hello Dart! ' 'Hello Flutter! ' 'Hello ImportV! ';
String s2 = 'Hello Dart! ' + 'Hello Flutter! ' + 'Hello ImportV! ';

// A string can be nested with an expression as ${expression}. If the expression is an identifier, {} can be omitted:
String s1 = 'Hello Flutter! ';
String s2 = 'Hello Dart! $s1Hello ImportV! ';
Copy the code

3. Boolean

// Boolean types default to null, literals only true and false, both of which are compile-time constants:
bool b = true;
Copy the code

4. List

// Define list method 1:
List lt1 = [1.2.3.4];

// Define list method 2:
List a = [];
a.add(1);
a.add(2);
a.add(3);

// Get list attributes:
List a = ['Dart'.'Flutter'.'ImportV'];
print(a.length);  // Get the list length
print(a.isEmpty);  // Determine if the list is empty, and if so, print true
print(a.isNotEmpty);  // Determine if the list is empty, if not, print true
print(a.reversed);  // Print the list in reverse order (flip the list)

// The index of the list starts at 0:
List a = [1.2.3.4];
print(a[0]);

// Splice and insert:
List a = ['Dart'.'Flutter'];
a.add('Android');  // Concatenate an element
a.addAll(['Android'.'iOS']);  // Concatenate multiple elements
a.insert(2.'Android');  // Insert an element. 2 is the index of the insertion position
a.insertAll(2['Android'.'iOS']);  // Insert multiple elements

// List to string:
List a = ['Dart'.'Flutter'.'Android'];
String b = a.join('- >');  Dart->Flutter->Android

// String list:
String a = 'Dart->Flutter->Android';
List b = a.split('- >');  Dart, Flutter, Android

// Specify the list type:
List a = <String> []; a.add('Flutter');
a.add(1);  / / an error

// Add the const keyword before the list literal to define an immutable list (compile-time constant) :
List a = const [1.2.3.4];
a[0] = 2;  / / an error
Copy the code

5. Set

A Set is an unordered Set whose elements cannot be repeated, and therefore cannot be retrieved by index.

// Define set method 1:
Set a = {'Dart'.'Flutter'.'ImportV'};

// define collection method two
Set a = {};
a.add('Dart');
a.add('Flutter');
a.add('ImportV');

// Create an empty collection:
Set a = {};  / / method
var a = <String> {};/ / method 2
var a = {};  // This creates an empty Map instead of a Set

// Get the number of elements in the set:
Set a = {'Dart'.'Flutter'.'ImportV'};
print(a.length);  // The output is 3

// Create an immutable collection (compile-time constants) :
Set a = const {'Dart'.'Flutter'.'ImportV'};
a.add('Android');  / / an error

// List to set:
List a = ['Dart'.'Flutter'.'Android'];
print(a.toSet());

// Set list:
Set a = {'Dart'.'Flutter'.'Android'};
print(a.toList());
Copy the code

6. Map

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.

// Define mapping method 1:
Map a = {
// key value
  'first': 'Dart'.'second': 'Flutter'.'third': 'Android'
  };

// define mapping method 2:
Map a = {};
a['first'] = 'Dart';
a['second'] = 'Flutter';
a['third'] = 'Android';

// Get mapping length:
print(a.length);

// Get the specified value:
print(a['first']);

// Add the const keyword before the mapping literal to define an immutable mapping (compile-time constant) :
Map a = const {'first': 'Dart'.'second': 'Flutter'.'third': 'Android'};
a['third'] = 'iOS'  / / an error
Copy the code

5. Operators

Here are the operators defined for Dart:

1. Arithmetic operators

In addition to basic arithmetic operations, Dart supports prefix and suffix, increment and decrement operators:

var a, b;
a = 0;

b = ++a;  // a increments by 1 and assigns to b
b = a++;  // a is assigned to b and increments by 1
b = --a;  // a decreases by 1 and assigns the value to b
b = a--;  // when a is assigned to b, the value decreases by 1
Copy the code

2. Type judgment operator

When the AS operator is used to cast an object to a specific type, it is usually considered to be an abbreviated form of the function called by the judged object after the is type has been determined. Consider the following code:

if (emp is Person) {
  emp.firstName = 'Bob';
}
Copy the code

Abbreviate using the AS operator:

(emp as Person).firstName = 'Bob';
Copy the code

[Note] The above code is not equivalent. If emP is null or not a Person object, then the first is example will not be executed later; The second AS example throws an exception.

3. Assignment operators

The following example uses several assignment and compound assignment operators, otherwise used similarly:

a = 123;  // Assign variables directly with =.b ?? =456;  / / use?? The = operator is assigned only if b is null

a *= 3;  // assign and multiply a = a * 3
Copy the code

4. Logical operators

Here is an example of a logical expression:

if(! done && (col ==0 || col == 3)) {
  / /... Do something...
}
Copy the code

5. Bit operators

Bitwise operators convert numbers to binary to work with:

If both corresponding binary bits are 1, the result is 1; otherwise, 0
print(a & b);  // The result is 4

// If either of the two corresponding binary digits is 1, the result bit is 1
print(a | b);  // The result is 14

// Bitwise xor, when the two corresponding binary bits are different, the result bit is 1, otherwise it is 0
print(a ^ b);  // Result is 10

// For each binary of the data, change 1 to 0 and 0 to 1
print(~a);  // I'm -13

// move the binary digits to the left of << to the left of several digits. The digits to the right of << specify the digits to move. Discard the high digits and fill the low digits with 0
print(a << 2);  // The result is 48, which is the same as multiplying by 2 ^ 2

// Move the binary digits to the left of << to the right of the number specified by the number of moves
print(a >> 2);  // The result is 3, which is the same thing as dividing by 2 ^ 2
Copy the code

Conditional expressions

Dart has two operators that sometimes replace if-else expressions to make them more concise, called conditional expressions:

condition ? expr1 : expr2

If the condition is true, execute expr1 (and return its value) : otherwise, execute and return the value of expr2.

expr1 ?? expr2

If expr1 is not null, return the value of expr1; Otherwise, execute and return the value of expr2.

Consider using the first method if the condition is based on a Boolean value, or the second method if it is based on null.

var a = 'Dart';
var b = 'Flutter';
var c = a ?? b.toUpperCase();  // The literal value of c is Dart
Copy the code

7. Cascade operators

Cascade operators.. You can implement a series of operations on the same object. In addition to calling functions, you can also access field properties on the same object. This can often save you the step of creating temporary variables while writing smoother code.

querySelector('#confirm')   // Get the object.
  ..text = 'Confirm'    // Call a member variable.
  ..classes.add('important')
  ..onClick.listen((e) => window.alert('Confirmed! '));
Copy the code

The first calls the function querySelector(), which returns the obtained object. The obtained objects execute the code following the cascade operator in turn, and the return value after the code execution is ignored.

The above code is equivalent to:

var button = querySelector('#confirm');
button.text = 'Confirm';
button.classes.add('important');
button.onClick.listen((e) => window.alert('Confirmed! '));
Copy the code

Cascade operators can be nested. Beware, however, of using cascade operators in functions that return objects. For example, the following code is incorrect:

var sb = StringBuffer(a); sb.write('foo')
  ..write('bar');   // sb.write() function calls return void, and cascading operations cannot be created on void objects.
Copy the code

6. Process control statements

The process control statements in Dart are similar to Java.

1. If-else branch

Unlike JavaScript, Dart’s criteria must be Booleans, not other types.

int a = 1;
if (a < 0) {
  a++;
} else if (a > 0) {
  a--;
}
Copy the code

2. The switch-case statement

The switch statement in Dart uses == to compare integer, string, compile-time constant, or enumeration types. The objects to be compared must all be instances of the same class (and cannot be subclasses), and the class must not be overridden on ==.

In case statements, each non-empty case statement must be followed by a break statement. In addition to break, continue, throw, or return can be used. When no case statement matches, the default code is executed:

var a = 'yes';
switch (a) {
  case 'yes':
    print('yes');
    break;
  case 'no':
    print('no');
    break;
  default:
    print('fault');
}
Copy the code

3. The for loop

To iterate, you can use the standard for statement. Such as:

// Compute the factorial of 5
int result = 1;
for (int i = 1; i < 6; i++) {
  result = result * i;
}
Copy the code

Closures capture the initial index value of the loop in Dart’s for loop to avoid a common trap in JavaScript. The following code prints 0 and 1, but in JavaScript it prints two 2’s in a row:

var callbacks = [];
for (var i = 0; i < 2; i++) {
  callbacks.add(() => print(i));
}
callbacks.forEach((c) => c());
Copy the code

4. While and do while loops

A while loop determines the execution condition before execution, while a do-while loop determines the execution condition after execution:

// Compute the factorial of 5
int i = 1;
int result = 1;
Use the while loop
while (i < 6) {
  result = result * i;
  i++;
}
// Use the do-while loop
do {
  result = result * i;
  i++;
} while (i < 6);
Copy the code

5. Break and continue

Use break to stop the program loop:

for (int i = 1; i < 5; i++) {
  if (i == 3) {
    break;
  }
  print(i);  // Output 1, 2 (loop ends when I = 3)
}
Copy the code

Use continue to jump to the next loop:

for (int i = 1; i < 5; i++) {
  if (i == 3) {
    continue;
  }
  print(i);  // The output is 1, 2, 4 (I = 3, skip to the next loop)
}
Copy the code

6. Other loops

Use for… in… Cycle:

// go through the number group
List a = ['Dart'.'Flutter'.'Android'];
for (var item in a) {
  print(item);
}
Copy the code

Using the forEach loop:

// go through the number group
List a = ['Dart'.'Flutter'.'Android'];
a.forEach((var item) {
  print(item);
});
Copy the code

7. An assert statement

Use the Assert statement. If the Boolean condition in the assert statement is false, normal program execution will be interrupted:

// Verify that the variable value is not empty.
assert(text ! =null);

// Make sure the variable value is less than 100.
assert(number < 100);
Copy the code

Assert statements are valid only in development environments and not in production environments. Assert in Flutter is only valid in Debug mode.

7. Exception handling

Dart code can throw and catch exceptions. Unlike Java, all exceptions in Dart are non-checked exceptions. Methods do not declare exceptions they throw, nor do they require any to be caught.

Dart provides the Exception and Error types, as well as several subtypes, as well as the ability to define your own Exception types. The Dart program can throw any non-NULL object, not just Exception and Error objects.

1. Throw an exception

Here is an example of throwing or throwing an exception:

throw FormatException('Expected at least 1 section');
Copy the code

We can also throw arbitrary objects:

throw 'Out of llamas! ';
Copy the code

2. try… catch… Finally catch exceptions

Dart allows code that may throw multiple types of exceptions to be handled by specifying multiple catch statements, and the exception is handled by the first catch statement that matches the type of exception thrown. If a catch statement does not specify a type, it can handle thrown objects of any type.

In addition, the catch() function can specify one or two arguments, the first being the exception object thrown and the second being the stack information.

When a finally statement is used, the code in finally is executed whether or not an exception is thrown.

Example code is as follows:

try {
  print(10~ /0);
} on IntegerDivisionByZeroException catch (e, s) {
  print(e);
  print(s);
} on Exception catch (e, s) {
  print(e);
  print(s);
}
Copy the code

Executing the above code outputs:

// Catch the exception
IntegerDivisionByZeroException  
// Stack information
#0      int.~/ (dart:core-patch/integers.dart:22:7)  
#1      main (file:///c:/Users/27884/Desktop/test.dart:3:14)
#2      _startIsolate.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:301:19)
#3      _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:168:12)
The result of the code execution after the finally statement
end
Copy the code

Eight, summary

That’s the first part of the Dart syntax I compiled. For more articles on Dart and Flutter, please follow my wechat account “Flutter Progress” for more resources