This is the fifth day of my participation in the August Wen Challenge.More challenges in August

Directory:

  1. basis
  2. variable
  3. The operator
  4. function
  5. object
  6. asynchronous

Basis.

1. The concept

  • Everything you can put in a variable is an object, and every object is an instance of a class. Numbers, functions, and NULL are all objects. All objects inherit from the Object class.
  • Although Dart is strongly typed, the type declaration is optional because Dart can infer types. To specify that no type is required, use the special type Dynamic.
  • Dart supports common types, such asList<int>(integer list) orList<dynamic>(List of objects of any type).
  • Dart supports top-level functions, such as main(), as well as functions bound to classes or objects (static and instance methods, respectively). You can also create functions within functions (nested or local).
  • Similarly, Dart supports top-level variables, as well as variables bound to classes or objects (static and instance variables). Instance variables are sometimes referred to as fields or attributes.
  • Unlike Java, Dart does not have public, protected, or private keywords. If an identifier begins with an underscore (_), the identifier is private to its library.
  • Identifiers can begin with a letter or underscore (_), followed by any combination of these characters plus numbers.
  • Sometimes it is important whether something is an expression or a statement, so these two words should be accurate.
  • The Dart tool can report two types of problems: warnings and errors. Warnings simply indicate that your code may not work, but they do not prevent your program from executing. Errors can be either compile-time or run-time. A compile-time error prevented the code from executing; Runtime errors cause code execution to throw exceptions.

2. Built-in types

  • Numbers (int and double)
  • strings
  • booleans
  • lists
  • maps
  • Runes (used to represent Unicode characters in strings)
  • symbols

3. The enumeration

Declare an enumeration type:

enum Color { red, green, blue }
Copy the code

Get the index of each value:

assert(Color.red.index == 0);
assert(Color.green.index == 1);
assert(Color.blue.index == 2);
Copy the code

Get all the values in the enumeration:

List<Color> colors = Color.values;
assert(colors[2] == Color.blue);
Copy the code

2. The variable

1. var

Like var in JavaScript, it can accept variables of any type, but the big difference is that once a var variable is assigned to Dart, its type is determined and it cannot be changed. (The difference is because Dart is a strongly typed language and any variable has a definite type.)

var t;
t = "pany";
// The following code will report an error in Dart because the variable t is already of type String
t = 1000;
Copy the code

2. The dynamic and Object

Dynamic, like var, is a keyword. Declared variables can be assigned to any object.

Object is the base class for all Dart objects, which means that all types are subclasses of Object (including Function and Null), so any type of data can be assigned to objects declared by Object.

Dynamic is similar to Object in that they declare variables that can change assignment types at a later time.

dynamic a; 
Object b;
a = "a";
b = 'b';
a = 1000; // No problem
b = 1000; // No problem
Copy the code

Dynamic differs from Object in that the compiler provides all possible combinations for objects declared as Dynamic, whereas Object can only use Object properties and methods, otherwise the compiler will report an error.

dynamic a;
Object b;
main() {
    a = "";
    b = "";
    printLengths();
}   
printLengths() {
    print(a.length); // no warning
    print(b.length); // warning:The getter 'length' is not defined for the class 'Object'
}
Copy the code

This feature of Dynamic makes it especially important to use, which can easily introduce a runtime error.

3. The final and const

If you never intend to change a variable, use final or const. The difference is that a const variable is a compile-time constant (reference and value cannot be changed), while a final variable is initialized the first time it is used (value can be changed).

Note: Instance variables can be final, but not const

// You can omit the String type declaration
final a = "a"; // final String str = "a"; 
const b = "b"; // const String str1 = "b";
Copy the code

The const keyword does not just declare constant variables. You can also use it to create constant values and declare constructors that create constant values. Any variable can be assigned a constant value:

var a = const [];
final a = const [];
const a = []; // same as const a = const [], because const is optional
Copy the code

4. Explicitly declare the type to be inferred

String name = 'pany';
String name = true; // This is an error
Copy the code

5. The default value

Variables that are not initialized have an initial value of NULL, and even variables that have a numeric type are initially null because numbers are objects like everything else in Dart.

The assert() call is ignored in production. Raises an exception in the development environment when the condition condition of assert(condition) is not true

int i;
assert(i == null);
Copy the code

Operator

Three common operators not found in JavaScript:

1.? . (Interview members based on conditions)

foo? .bar =4;
Copy the code

foo? Bar gets the bar property, or returns null if foo is empty

2… Level (al)

Note: Strictly speaking, cascading “..” The notation is not an operator; it’s just part of the Dart syntax.

  List<int> listInt = List()
    ..add(0)
    ..add(1)
    ..add(2)
    ..removeAt(1);
  print(listInt); / / [0, 2)
Copy the code

3.??

var a = b ?? 'pany';
Copy the code

Return ‘pany’ if b is null, otherwise return the value of b

Function of 4.

1. Function declaration

bool isNoble(int a) {
  return_nobleGases[a] ! =null;
}
Copy the code

2. Functions as arguments

typedef bool CALLBACK();

// The return type is not specified. The default is dynamic, not bool
isNoble(int a) {
  return_nobleGases[a] ! =null;
}

void test(CALLBACK cb){
   print(cb()); 
}
// isNoble is not a bool
test(isNoble);
Copy the code

3. Shorthand for function declarations

bool isNoble(inta) => _nobleGases[a] ! =null ;
Copy the code

4. Function expressions

var say = (str) {
  print(str);
};
say("hi world");
Copy the code

5. Optional position parameters

String say(String from, String msg, [String device]) {
  var result = '$from says $msg';
  if(device ! =null) {
    result = '$result with a $device';
  }
  return result;
}

say('Bob'.'Howdy');
say('Bob'.'Howdy'.'smoke signal');
Copy the code
  • Bob says Howdy
  • Bob says Howdy with a smoke signal

6. Optional named parameters

// Set the bold and hidden flags
void enableFlags({bool bold, bool hidden}) {
    // ... 
}

enableFlags(bold: true, hidden: false);
Copy the code

Note: You cannot use both positional and named parameters.

Lexical closures

Function makeAdder(num addBy) {
  return (num i) => addBy + i;
}

void main() {
  var add2 = makeAdder(2);
  var add4 = makeAdder(4);
  print(add2(3) = =5); // true
  print(add4(3) = =7); // true
}
Copy the code

MakeAdder () captures the variable addBy. Wherever the returned function goes, it remembers addBy.

8. Determine function equality

void foo() {} // Top-level function

class A {
  static void bar() {} // Static method
  void baz() {} // Instance method
}

void main() {
  var x;
  // Compare top-level functions
  x = foo;
  print(foo == x); // true
  // Compare static methods
  x = A.bar;
  print(A.bar == x); // true
  // Compare instance methods
  var v = A();
  var w = A();
  var y = w;
  x = w.baz;
  print(y.baz == x); // true
  print(v.baz ! = w.baz);// true
}
Copy the code

9. If no value is specified, the function returns NULL

foo() {}
print(foo() == null); // true
Copy the code

Object of five.

1. Determine whether two objects are equal: identical

  • Here we use a constant constructor as an example (to create compile-time constants using the constant constructor, place the const keyword before the constructor name)
  • Constructing two identical compile-time constants produces a single, canonical instance (as in the following example)
var a = const ImmutablePoint(1.1);
var b = const ImmutablePoint(1.1);
assert(identical(a, b)); // They are the same instance
Copy the code

2. Obtain the object type: runtimeType

print('Object A is of type:${a.runtimeType}');
Copy the code

constructor

Note: 1. Constructors do not inherit. 2. Classes with no constructors have default constructors (no arguments, no name).

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

Named constructors:

class Point {
  num x, y;
  Point(this.x, this.y);
  Point.origin() { // Name the constructor
    x = 0;
    y = 0; }}Copy the code

Of course, there are other constructors, such as “factory constructors”, the previously mentioned “constant constructors”, and so on…

6. The asynchronous

The Dart library has many functions that return Future or Stream objects. These functions are called asynchronous functions.

1. Future

Future is basically the same as Promise in JavaScript.

1.1. The Future. Then

// Simulate a time-consuming task with future.delayed
Future.delayed(new Duration(seconds: 2), () {return "hi world!";
}).then((data){
   print(data); // Print "Hi world!" after 2 seconds.
});
Copy the code

1.2. Catching exceptions:

1.2.1 Future. CatchError:
Future.delayed(new Duration(seconds: 2), () {// return "hi world!" ;
   throw AssertionError("Error");  
}).then((data){
   // Successful execution will go here
   print("success");
}).catchError((e){
   // Execution failure leads to this
   print(e);
});
Copy the code
1.2.2 onError:
Future.delayed(new Duration(seconds: 2), () {
    // return "hi world!" ;
    throw AssertionError("Error");
}).then((data) {
    print("success");
}, onError: (e) {
    print(e);
});
Copy the code

1.3. The Future whenComplete

Usage scenario: A loading dialog box is displayed before a network request, and the dialog box is closed after the request.

Future.delayed(new Duration(seconds: 2), () {// return "hi world!" ;
   throw AssertionError("Error");
}).then((data){
   // Successful execution will go here
   print(data);
}).catchError((e){
   // Execution failure leads to this
   print(e);
}).whenComplete((){
   // Success or failure will lead us here
});
Copy the code

1.4. The Future. Wait

Future.wait([
  // Return the result after 2 seconds
  Future.delayed(new Duration(seconds: 2), () {
    return "hello";
  }),
  // Return the result after 4 seconds
  Future.delayed(new Duration(seconds: 4), () {
    return " world";
  })
]).then((results){
  print(results[0]+results[1]); // Print "Hello world" after 4 seconds
}).catchError((e){
  print(e);
});
Copy the code

2. async/await

Async /await is exactly the same as async/await in JavaScript, notes skipped here.

Whether in JavaScript or Dart, async/await is just a syntactic sugar that the compiler or interpreter will eventually convert into a Promise (Future) call chain.

3. Stream

A Stream is also used to receive asynchronous event data and, unlike a Future, can receive the results (success or failure) of multiple asynchronous operations. That is, success or failure events can be fired multiple times to pass result data or error exceptions while performing an asynchronous task. Stream is commonly used in asynchronous task scenarios where data is read multiple times, such as network content download and file read and write.

Stream.fromFutures([
  // Return the result after 1 second
  Future.delayed(new Duration(seconds: 1), () {
    return "hello 1";
  }),
  // Throw an exception
  Future.delayed(new Duration(seconds: 2), () {throw AssertionError("Error");
  }),
  // The result is returned after 3 seconds
  Future.delayed(new Duration(seconds: 3), () {
    return "hello 3";
  })
]).listen((data){
   print(data);
}, onError: (e){
   print(e.message);
},onDone: (){

});

// Output:
I/flutter (17666): hello 1
I/flutter (17666): Error
I/flutter (17666): hello 3
Copy the code

Reference:

Flutter Practice and Dart2 Chinese documents