1 variable

1.1 Declaration of variables

Var, Dynamic, Object

① Uninitialized variable declarations

Var, dynamic, Object If a variable is not initialized, the value of the variable can be changed dynamically, as shown in the following example

void main() {
  var a;   //a stands for variable name, you can choose any name
  a = 1;
  a = "data";
  
  dynamic a2;  
  a2 = 1;
  a2 = "a2";
  
  Object a3; 
  a3 = 333;
  a3 = "a3";
}
Copy the code

② Initialize variable declarations

Similarities:

You can declare variables directly, as shown in the following example

var d1 = 123; // type d1 is inferred to be type int
dynamic d2 = "123"; The d2 type is inferred to be a string type
Object d3 = "1234";
Copy the code

Difference:

  1. Var declares that the type cannot be changed after initialization, whereas Dynamic and Object do.
  2. The dynamic compile phase does not check the type, whereas the Object compile phase checks the type;

Look at the following example

  var d1 = 123; // type d1 is inferred to be type int
  d1 = 1234;
// d1 = "1123"; // An error is reported if written as a string

  dynamic d2 = "123"; The d2 type is inferred to be a string type
  d2 = 123; / / can
  
  Object d3 = 123; //d3 is inferred to be an int
  d3 = "123"; / / can

  dynamic d = "1234";
  Object o = "121";
  d.test();
// o.test(); // Do not compile
Copy the code

The default value of 1.2

① Uninitialized variables automatically get a default value of NULL

② All objects!! The default value of the object is null

1.3 final and const

Thing in common:

  1. The declared type can be omitted, as shown in the following example
final str = "str"; //final String str = "str"; The String type can be omitted
const str2 = "str2"; //const String str2 = "str2"; Like final, String can be omitted
Copy the code
  1. No more assignment after initialization (as in Java);
  2. It cannot be used with var, as shown in the following example
final ~~var~~ f1 = ""; // Error cannot be used together with var
const~ ~var~~ f2 = ""; // Error cannot be used together with var
Copy the code

Differences (note) :

  1. Class level constants, using static const; The following figure shows DateTime source code as an example

  1. Const can initialize its value with the value of another const constant; Look at the following example
const a = 1; 
const b = 2; 
var c = 3; 
final d =4; 
const sum = a+b;// Yes, it is running properly
const sum2 = a+c;// c is not const
const sum3 = a+d;// error: d is not const
Copy the code
  1. Const assignment declaration, const can be omitted; Look at the following example
const list1 = []; 
const list2 = const [];/ / const can be omitted
Copy the code
  1. You can change the value of a nonfinal, nonconst variable, even if it once had a const value; Look at the following example
var list = const [1.2.3]; 
list = [3.2.1]; 
print(list);// the output is [3,2,1]
Copy the code
  1. Immutability resulting from const is transitive; Look at the following example
  final list1 = [1.2.3];
  list1[0] = 0;
  print(list1);// output is [0,2,3]
  const list2 = [1.2.3];
  list2[0] = 0;// An error is reported and cannot be modified
   print(list2);List2 cannot be modified
Copy the code
  1. The same const constant is not created twice in memory; Look at the following example
const a = 1; 
const b =1; 
const c =2; 
print(identical(a,b));//true 
print(identical(a,c));//false
Copy the code
  1. Const needs to be a compile-time constant;
const dt = DateTime.now();Const must be a compile-time constant
final dt1 = DateTime.now();// Yes, it is running properly
Copy the code

2 Built-in Types

type explain type explain
Numbers The numerical Sets A collection of
Strings string Maps A collection of
Booleans Boolean value Runes Symbol character
Lists List (array) Symbols identifier

2.1 Built-in types -num, int, and double

  • Int: integer value;
  • Double: 64-bit double precision floating point number;
  • Int and double are subclasses of num;

2.2 Built-in Type -String

  1. The Dart string is a SEQUENCE of UTF-16 encoded characters that can be created using either single or double quotation marks;
  2. You can create a multi-line string object with three single or double quotation marks;
  3. You can create “raw” strings using the r prefix; Look at the following example
String s1 = "123" 'abc' "okok";
String s2 = "123" + 'abc';
String s3 = ' ''ewrwerAeawrwer eee'' ';
String s4 = ' ''ewrwerAeawrwer\neee'' ';
String s5 = r' ''ewrwerAeawrwer\neee'' ';
print(s1);
print(s2);
print(s3);
print(s4);
print(s5);
Copy the code

Running results:

123abcokok
123abc
ewrwerAeawrwer
  eee
ewrwerAeawrwer
eee
ewrwerAeawrwer\neee
Copy the code

Now that you’ve tried String, try StringBuffer as shown in the following example

StringBuffer sb1 = StringBuffer();
StringBuffer sb2 = StringBuffer();
sb1.write("333");
sb1.write("aaa");
sb1.write("666"); sb2.. write("333").. write("aaa").. writeAll(['6'.'6'.'6']);/ /.. Cascade character, can be called inside the chain method
print(sb1);//333aaa666
print(sb2);//333aaa666
Copy the code

A StringBuffer object can be printed without calling the.toString() method. Why? Let’s take a look at how print() is implemented internally. See below, it turns out that it prints the toString() method of the called object.

4. We can use expressions in strings:${expression}If the expression is an identifier, you can omit {}. If the result of the expression is an object, Dart calls the object’s toString() function to get a string. Look at the following example

var a = 1; 
var b = 2; 
print("${a + b}"); // Output: 3
Copy the code

2.3 Built-in Type -bool

  • Unlike Java, bool objects default to null for uninitialization; Look at the following example
bool bo; 
print(bo);// output: null if(bo){// error, because bool is not initialized default is null, so this call will run error}
Copy the code

Dart’s List doesn’t look exactly like a List. It’s a bit like an array in Java. Dart can print lists directly, including elements of lists, which are also objects. In Java, printing a list directly results in the address value. The subscript index of a List in Dart starts at 0, as in Java. Generics are supported as in Java. Add, delete, change, check, support reverse order, own sort, shuffle, you can use + to merge two lists.

/ / declare
  // Automatic length
  List growableList = List();
//  List growableList = new List()..length = 3;growableList.. add(1).. add(2).. add('damon');
  print('growableList: ${growableList}');
  // Fixed length
  var list = List(3); //List declaration, can use var or List.
  list[0] = 1; // The subscript index starts at 0
  list[1] = 2;
  list[2] = 'damon';
  print('list: ${list}');
  // The element type is fixed
  var typeList = List<int>();
  typeList.add(1);
  typeList.add(2);
  typeList.add(3);
  print('typeList: ${typeList}');
  // Common attributes
  int first = typeList.first;
  print('typeList.first: ${first}'); // The first element
  int last = typeList.last;
  print('typeList.last: ${last}'); // The last element
  int length = typeList.length;
  print('typeList.length: ${length}'); // Number of elements
  bool isEmpty = typeList.isEmpty;
  print('typeList.isEmpty: ${isEmpty}'); // Whether it is empty
  bool isNotEmpty = typeList.isNotEmpty;
  print('typeList.isNotEmpty: ${isNotEmpty}'); // Whether it is not null
  Iterable reversed = typeList.reversed;
  print('typeList.reversed: ${reversed}'); / / reverse
  // Add, delete, change, sort, shuffle, copy sublist
  var list4 = [];
  / / to add
  list4.add(1);
  print('add 1 :${list4}');
  list4.addAll([2.3.4]);
  print('addAll [2, 3, 4] :${list4}');
  list4.insert(0.0);
  print('insert(0, 0) :${list4}');
  list4.insertAll(1[5.6.7]);
  print('insertAll(1, [5, 6, 7]) :${list4}');
  / / delete
  list4.remove(5);
  print('remove 5 :${list4}');
  list4.removeAt(2);
  print('remove at 0 :${list4}');
  / / change
  list4[4] = 5;
  print('update list4[4] to 5 :$list4}');
  //range
  list4.fillRange(0.3.9);
  print('fillRange update list4[0]-list4[2] to 9 :$list4}');
  Iterable getRange = list4.getRange(0.3);
  print('getRange list4[0]-list4[2] :$getRange}');
  / / check
  var contains = list4.contains(5);
  print('list4 contains 5 :${contains}');
  var indexOf = list4.indexOf(1);
  print('list4 indexOf 1 :${indexOf}');
  int indexWhere = list4.indexWhere((test) = > test == 5);
  print('list4 indexWhere 5 :${indexWhere}');
  / / sorting
  list4.sort();
  print('list4 sort :${list4}');
  / / shuffle
  list4.shuffle();
  print('list4 shuffle :${list4}');
  // Copy the sublist
  var list5 = list4.sublist(1);
  print('sublist(1) list5 :${list5}');
  / / operators
  var list6 = [8.9];
  print('list6 :${list6}');
  var list7 = list5 + list6;
  print('list5 + list6 :${list7}');
Copy the code

If you look at the figure below, this is a List that has some common attributes that we know when we use them, so I’m not going to illustrate them here.

2.5 Built-in Types -Map

/ / declare
  // Dynamic type
  var dynamicMap = Map(a); dynamicMap['name'] = 'dongnao';
  dynamicMap[1] = 'android';
  print('dynamicMap :${dynamicMap}');
  / / type
  var map = Map<int, String> (); map[1] = 'android';
  map[2] = 'flutter';
  print('map :${map}');
  // It can also be declared like this
  var map1 = {'name': 'dongnao'.1: 'android'};
  map1.addAll({'name':'damon'});
  print('map1 :${map1}');
  // Common attributes
// print(map.isEmpty); // Whether it is empty
// print(map.isNotEmpty); // Whether it is not null
// print(map.length); // Number of key-value pairs
// print(map.keys); / / key collection
// print(map.values); / / the value set
Copy the code

Map is similar to Java in that it has key-value pairs, which we know when we use them, but we won’t go through all the examples here.

2.6 Built-in Type -Set No duplicate list

var dynamicSet = Set(a); dynamicSet.add('dongnao');
  dynamicSet.add('flutter');
  dynamicSet.add(1);
  dynamicSet.add(1);
  print('dynamicSet :${dynamicSet}');
  // Common attributes are similar to list
Copy the code

The basic usage of Set is similar to Java, with a few differences. Set1.difference (set2): returns the set of elements present in set1 but not in set2; Set1. intersection(set2) : Returns the intersection of set1 and set2; Set1. union(set2) : returns the union of set1 and set2; Set1.retainall () : set1 only preserves certain elements (the elements to be retained must exist in the original set);

  • Look at the following example:
  Set set1 = Set(a); set1.addAll(['a'.'b'.'a'.'c'.'d']);
  Set set2 = Set(a); set2.addAll(['a'.'b'.'a'.'e'.'f']);
// print(set1.difference(set2)); {c, d}
// print(set1.intersection(set2)); {a, b}
// print(set1.union(set2)); {a, b, c, d, e, f}
  set1.retainAll(['a'.'b']);//set1 preserves only certain elements (the elements to be preserved must exist in the original set)
  print(set1);{a, b}
Copy the code

2.7 Built-in types -Runes

  • Dart Runes is a String object in the UTF-32 character set.
  1. Runes is used to represent Unicode characters in strings;
  2. Display character graphs using string.fromCharcodes;
  3. If there are more than four values, place the encoded value in braces.
  • Look at the following example
Runes runes = new Runes('\u6787 \u2665 \u{1f605} \u{1f60e} \u{1f44d}'); 
print(String.fromCharCodes(runes));// Py? ? ?
Copy the code

Output result:

Py ♥ 😅 😎 👍Copy the code

CopyChar | free special symbol, can refer to it.

2.8 Built-in type -Symbol

  1. The symbol literal is a compile-time constant preceded by the #; Look at the following example
#foo_lib 
#runtimeType
Copy the code
  1. If it is determined dynamically, use the Symbol constructor to instantiate it via new. Look at the following example
Symbol obj = new Symbol('name');
Copy the code

The mirrors module has been removed. The mirrors module is no longer used for reflection.

3 function

3.1 Function Definition

  1. Dart functions are objects of type Function;
  2. All functions return values. If no return value is specified, the statement is defaultreturn null;Execute as the last statement of the function;
  3. Omit types when defining functions (not recommended); Look at the following example
/** * type does not omit type */ 
int add2(int a, int b) { 
    return a + b; 
    } 
/** 1. Parameter types and method return types are omitted (not recommended) */ 
add(a,b){ 
    return a+b; 
    }
Copy the code
  1. For methods that have only one expression, you can choose to define them using the abbreviated syntax => (Kotlin implements =), a bit like Lambda; Look at the following example
/** 3 
int add(int a, int b) { 
    return a + b; 
    } 
/** 4 
int add(int a, int b) =>a+b;
Copy the code
  1. Function can be defined inside the function, support nesting; Look at the following example
add1() { 
     int add2(int a, int b) => a + b;
       }
Copy the code

3.2 Optional Parameters

  1. Optional named parameters: use {param1, param2… } to specify named parameters.
  int add({int x, int y, int z}){ x ?? =1; y ?? =2; z ?? =3;
    return x + y + z;
  }

  print(add());
  print(add(x : 1.y : 2));
  print(add(x : 1.y : 2.z : 0));
  print(add3(z : 1.y : 2));
Copy the code
  1. Optional positional parameters: place optional parameters in [], and mandatory parameters in front of optional parameters.
  int add4(int x, [int y, int z]){ y ?? =2; z ?? =3;
    return x + y + z;
  }
  print(add4(1));
  print(add4(1.3));
  print(add4(1.6.6));
Copy the code
  1. Optional named parameter defaults (which must be compile-time constants) can be used with equal sign ‘=’ or colon ‘:’. (Prior to Dart SDK 1.21, only colons were available, colon support will be removed later, so use equals is recommended.)
int add5(int x, {int y = 2, int z = 3}) { 
    return x + y + z; } 
    // The required parameter in front has no name
    print(add5(1.y: 10.z: 2));
Copy the code
  1. The default value for optional positional arguments (the default value must be a compile-time constant) can only be used with the equal sign ‘=’.
int add6(int x, [int y = 2, int z = 3]) { 
    return x + y + z; 
    } 
    print(add6(1));
Copy the code
  1. You can use list or map as defaults, but it must be const.
void func( 
    {List list = const [1.2.3].Map map = const {1: 1.'name': 'dongnao'}}) { 
    //TODO ... 
    }
Copy the code

3.3 Anonymous Functions

  1. No arguments anonymous
var printFunc = () = > print("666");
printFunc(); // This is syntactically supported, but not recommended
(() = > print("666"()));Copy the code
  1. Do. Anonymous
var printFunc1 = (name) = > print("$name"); 
printFunc1('The Bald King');
Copy the code
  1. Anonymous functions pass parameters
 List test(List ls, String fun(str)) {
    for (int i = 0; i < ls.length; i++) {
      ls[i] = fun(ls[i]);
    }
    return ls;
  }
  List ls = ['a'.'b'.'c'];
  print( test(ls, (str) = > str * 2));
Copy the code

Output result:

[aa, bb, cc]
Copy the code

ForEach List forEach List forEach

It’s actually a circular call passed inf(element)Method, see the following example:

List ls = ['a'.'b'.'c']; 
ls.forEach((ele) = > print(ele));
Copy the code

Output result:

a
b
c
Copy the code
  1. Closure (return Function object)
Function makeAddFun(int a) { 
   a++; 
   return (int b) = >a+b; 
   } 
   print(makeAddFun(1) (2));Var f = makeAddFun(1); print(f(2));
Copy the code

Output result:

4
Copy the code
  1. Function is an alias
void main(){
  MyFunc myFunc = subtsract(2.1);
  myFunc = add(2.2);
  myFunc = divide(4.2);
  calculator(2.1, subtsract);
}

typedef MyFunc(int a, int b);
Define two functions according to the same function signature of MyFunc
add(int a, int b) {
  print('add:${a + b}');
}

subtsract(int a, int b) {
  print('subtsract: ${a - b}');
}

divide(int a, int b) {
  print('divide: ${a / b}');
}
Copy the code

Output result:

Subtsract:1Add:4Divide:1Subtsract:1
Copy the code

4 operator

4.1 Postfix operators? .

  • Conditional member access is similar to. Except that the operation object on the left cannot be null, such as foo? Bar Returns null if foo is null, otherwise returns the bar member
Stringa; print(a? .length);Copy the code

Output result:

null
Copy the code

4.2 The quotient operator ~/

  • ÷ divisor = quotient… The remainder, A ~/ B = C, is the quotient. The Java equivalent of /
print(2 / 3); // The output is 0.666666666666
print(2 ~/ 3); // Output: 0Copy the code

4.3 Type determination operator

  • Type determination operator:as,is,is!Determine object types at run time
// As type conversion
  num iNum = 1;
  num dNum = 1.0;
  int i = iNum as int;
  double d = dNum as double;
  print([i, d]);

// String s = iNum as String; // Cannot convert, error reported

  //is Returns True if the object is the specified type
  print(iNum is int);
  Child child;
  Child child1 = new Child();
  print(child is Parent); //child is Null
  print(child1 is Parent);

  //is! Returns False if the object is of the specified type
  print(iNum is! int);
Copy the code

4.4 Conditional Expressions

  bool isFinish = true;
  String txtVal = isFinish ? 'yes' : 'no';
  // expr1 ?? Expr2, if expr1 is non-null, returns its value; Otherwise, exPR2 is executed and the result is returned.
  bool isPaused;
  isPaused = isPaused ?? false;
  / / orisPaused ?? =false;
Copy the code

4.5 Cascade Operators

  • .Multiple functions can be called consecutively on the same object and member variables can be accessed.

    Strictly speaking, the two-point concatenation is not an operator. Just a Dart special syntax.
StringBuffer sb = newStringBuffer(); sb .. write('dongnao') 
  ..write('flutter') 
  ..write('\n') 
  ..writeln('damon');
Copy the code