I. Important concepts

  • 1. All variables are referenced objects, and objects are instances of a class. Numbers, functions, and NULL are all objects. All classes inherit from Object.
  • 2.Dart can be inferred by type or specified by type.
  • 3.Dart does not have Java’s public,protected, and private member access qualifiers. Instead, it uses underscores (_) to indicate that it is private.
  • 4.Dart expressions are different from statements. Expressions have values and statements have no values. Like the conditional expression condition? Expr1: expr2 contains the value expr1 or expr2. In contrast to if-else branch statements, if-else branch statements have no value.
    1. The default value for uninitialized variables in Dart is NULL.

Data type

1. The final and const

Const is more strict than final.

  • 1. Final and const are both declaratively assigned, but final assignments are the same as var assignments. Const assignments must be compile-time constants.
  • 2. The properties of the final reference object are mutable, but the reference object itself cannot be. Const in Dart cannot change an attribute value within an object;
  • When declaring a class member variable,const must be static

2. Built-in types

1. The Number type

Number contains int, double;

Int integer value; The value contains a maximum of 64 characters and varies with platforms. On DartVM, the value is between -263 and 263-1. The Dart compiled into JavaScript uses JavaScript numbers, which are allowed to range from -253 to 253-1.

A 64-bit double – precision floating – point number that complies with IEEE 754 standards.

2. Type String

The Dart string is a SEQUENCE of UTF-16 encoded strings.

    1. Both single and double quotes create strings
    1. ${expression} can insert values into strings, or omit {} if the expression is a single identifier (such as a single variable).
    1. The + sign concatenates strings, and three or three double quotes create multi-line strings
    1. Adding r to a string creates a “raw” string (strings are not processed)
    1. Statement compile-time constants String, interpolation expressions should be compile-time constants (null, String, Number, Boolean)
3. The Boolean type

Dart should be explicit, not js like var STR = “; If (STR) {XXX} else {XXX} should be used instead if (str.isempty) {XXX} else {XXX}

Dart uses the bool keyword to represent Boolean types, which have only two objects, true and false, both of which are compile-time constants.

4. List types

JavaScript like array

  • 1. If a new type is added after the type is inferred, an error message is displayed.
  • 2. Provides extensions (…) And null – aware (… ?). Javascript-like (…) The null-aware operator prevents a variable from being deconstructed as null
  • 3. Provides if or for to build collections.
var listOfInts = [1, 2, 3];
var listOfStrings = [
  '#0',
  for (var i in listOfInts) '#$i'
];

var nav = [
  'Home',
  'Furniture',
  'Plants',
  if (promoActive) 'Outlet'
];
Copy the code
5. The Set type

A set is an unordered collection of specific elements. Duplicate values are also not allowed. The statement Set:

// Var halogens = {' tavern ', 'chlorine', 'bromine', 'whisper ',' actin '}; // create a Set of type +{}. var names = <String>{}; Set<String> names = {};Copy the code
6. The Map types

Javascript-like map.

There are two ways to declare a Map:

Var gifs = {// key: value 'first': 'partridge', 'second': 'turtledoves', 'fifth': 'golden rings'}; Var gifs = Map(); gifs['first'] = 'partridge'; gifts['second'] = 'turtledoves'; gifts['fifth'] = 'golden rings';Copy the code
7. Type with Runes

In Dart, Runes exposes Unicode code points for strings. Starting with Dart2.6, runes can be accessed and manipulated using the characters package

8. The Symbol type

A Symbol object represents a DART declared identifier or operator. Usually write code to use little, temporarily skip.

Three functions.

1. Function declaration

Dart functions are roughly similar to JavaScript functions; Belongs to Function; All functions return a value. If not, return NULL is implicitly added. The declaration is as follows:

    1. The return value of the function can be omitted, but Dart is a typed language and the return value should be written in. Void is the best way to write a return value
    1. A required parameter is preceded by @required
    1. [] is an optional parameter
    1. You can use the “=” sign to provide default values for function arguments.
    1. Anonymous functions differ from JavaScript declarations in that they omit the function keyword, or the arrow of the function, as shown below
Function name (type param1 = XXX, @required Type param2, [type param3, type param4...]) ) {/ / function body} / / anonymous function declarations ([[Type] param1 [,...]]) {codeBlock; }; Var list = ['apples', 'bananas', 'oranges']; list.forEach((item) { print('${list.indexOf(item)}: $item'); });Copy the code

Lexical scope

Dart is lexical scoped. Variables are fixed scoped, meaning that the scope of a variable is determined at code writing time.

3. The closure

A closure is a function object that calls a function object that is not in its lexical scope, but still has access to variables in the lexical scope of the function object.

Function makeAdd(int n2) { return (int n) => n2 + n; } void main() { Function func1 = makeAdd(2); Function func2 = makeAdd(3); print(func1(4)); // 6 print(func2(8)); / / 11}Copy the code

Operator

1. Arithmetic operators

The operator note The sample
~ / Take more than an integer print(5 ~/ 2); // The result is 2
is Type judgment var p1 = ‘123123’; print(p1 is String); // Result is true
is! Type judgment With is the opposite
as Forced type conversion var p1 = ‘123123’; String p2 = p1 as String; print(p2 is String); // Result is true
?? = The value is assigned when the assigned variable is null

Control flow statement

1. try catch finally

Unlike Java, all exceptions in Dart are non-checked exceptions (run-time exceptions, not compile-time 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. You can also define your own exception types. However, the Dart program can throw any non-NULL object, not just Exception and Error objects.

Catch can specify a type to catch certain types of errors, or none to catch all types of errors.

try { breedMoreLlamas(); } on OutOfLlamasException {// a special exception buyMoreLlamas(); } on Exception catch (e) {print('Unknown Exception: $e'); Print ('Something really unknown: $e'); print('Something really unknown: $e'); }Copy the code

Class six.

  • Dart is an object-oriented language based on classes and mixin inheritance;
  • All classes inherit from Object;
  • Based on the mixin inheritance mechanism, each class has only one superclass

Constructor declaration

(1) Default constructor. If no constructor is declared in a class, Dart provides a default constructor that takes no arguments and calls the parent class’s no-argument constructor by default. However,Dart does not provide a default constructor if any of the constructors exist in the class.
Class Point {num x, y; } // There is no default constructor for this class because there is a named constructor in the class. Point.origin() { x = 0; y = 0; }}Copy the code
(2) Name the constructor. A class can implement multiple named constructors. Facilitate clear expression of purpose; A subclass cannot inherit the constructor of its parent class;
Class Point {num x, y; Point.origin() { x = 0; y = 0; }}Copy the code
(3) Call the superclass named constructor. The constructor of the parent class is called after the current class constructor: and before the function body

This cannot be accessed to the right of:

The execution sequence is as follows:

  • 1. Initialize the parameter list
  • 2. Superclass constructor
  • 3. Subclass constructor
Class Person {String firstName; Person.fromJson(Map data) { print('in Person'); this.firstName = data['firstName']; } // Subclass extends Person {String s; Employee.fromjson (Map data, String s) : super.fromjson (data) {print('in Employee'); this.s = s; }} void main(List<String> arguments) { In Employee e = new employee. fromJson({'firstName': 'shen'}, 'hahaha '); }Copy the code
(5) Initialize the parameter list

Method 1: Use grammar sugar

class Point { num x, y; // Point(this.x, this.y); // Point(this.x, this.y); }Copy the code

Method 2: Initialize on the right side of: (This cannot be accessed on the right side of:)

class Point { num x, y; Point(this.x, this.y); Print ('In point.fromjson (): print('In point.fromjson (): print('In point.fromjson (): print('In point.fromjson (): print('In point.fromjson (): print('In Point. ($x, $y)'); }}Copy the code
(6) Redirect constructor

Sometimes the only purpose of a constructor is to redirect to another constructor in the same class. The body of the redirected constructor is empty, and the constructor is called after the colon (:).

class Point { num x, y; // The main constructor of the class. Point(this.x, this.y); AlongXAxis (num x) : this(x, 0); }Copy the code
(7) Constant constructor

If the objects generated by this class are fixed, they can be defined as compile-time constants.

class ImmutablePoint {
  static final ImmutablePoint origin =
      const ImmutablePoint(0, 0);

  final num x, y;

  const ImmutablePoint(this.x, this.y);
}
Copy the code
(8) Factory constructor

The factory constructor cannot access this.

The factory keyword is used when executing the constructor does not always create a new instance of the class.

class Logger { final String name; bool mute = false; // _cache is a private attribute, as can be seen from the named _. static final Map<String, Logger> _cache = <String, Logger>{}; factory Logger(String name) { if (_cache.containsKey(name)) { return _cache[name]; } else { final logger = Logger._internal(name); _cache[name] = logger; return logger; } } Logger._internal(this.name); void log(String msg) { if (! mute) print(msg); }}Copy the code

2. Constructor usage

The new keyword is optional in Dart 2.

Create objects through constructors. The constructor name can be either className or classname.identifier.

class Person { String firstName; Person.fromJson(Map data) { print('in Person'); Var p1 = Point(2, 2); Var p2 = point.fromjson ({'x': 1, 'y': 2});Copy the code

3. Obtain the object type

The type of the object can be returned at runtime using the object’s attribute runtimeType

/ * -- -- -- -- -- -- -- -- -- -- a sample -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - * / var emp = new Employee in fromJson ({}); print('The type of emp is ${emp.runtimeType}'); / / return the Employee / * -- -- -- -- -- -- -- -- -- -- example 2 -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - * / var emp = new Employee in fromJson ({}); emp.firstName = 'Bob'; print('The type of emp is ${emp.firstName.runtimeType}'); / / return a StringCopy the code

4. Class instance variables

Class instance variables default to null, and non-final instance variables default to declare implicit getters and setters. If a class instance variable is already assigned at the declaration, the assignment is executed before the constructor executes.

class Person { String firstName = 'shen'; Person.fromjson (Map data) {// The assignment to the property will print(this.firstname) before the constructor is executed; print('in Person'); } } main() { var emp = new Person.fromJson({}); }Copy the code

Method 5.

Methods are functions that provide behavior for an object.

(1) method

class Point { num x, y; Point(this.x, this.y); num distanceTo(Point other) { var dx = x - other.x; var dy = y - other.y; return (dx * dx + dy * dy); }} void main() {Point p1 = new Point(1,2); Point p2 = new Point(2,4); print(p1.distanceTo(p2)); }Copy the code

(2) set and get

Declare get and set. Do not duplicate existing properties. This is different from Java and other languages where get and set can do the effect of calculating properties.

class Point {
  num x, y;
  Point(this.x, this.y);
  // 显式声明属性n的get方法
  num get n => x + 10;
  // 显式声明属性n的set方法
  set n (num value) {
    this.y += 100;
  }
}

void  main() {
  Point p1 = new Point(1,2);
  print(p1.n);
  p1.n = 200;
  print(p1.y);
}
Copy the code