1 introduction

Dart is a computer programming language developed by Google that can be used for the Web, servers, mobile applications and the Internet of Things.

Dart was born in 2011 as a replacement for JavaScript. But the past few years have been tepid. Until the appearance of Flutter is now taken seriously again.

To learn Flutter we must first be able to Dart.

Liverpoolfc.tv: dart. Dev /

2 Environment Construction

To develop Dart applications locally, you first need to install the Dart SDK.

Official document: dart.dev/get-dart.

Windows environment

www.gekorm.com/dart-window… .

MAC environment

Referring to the previous article, Mac constructs the Flutter+Dart development environment.

3 Development Tools

Dart development tools are numerous: IntelliJ IDEA, WebStorm, Atom, VS Code, and more

Here we’ll show you how to configure Dart in VS Code.

1 Install VS Code code.visualstudio.com/.

2 Locate the VS Code plug-in to install dart.

3 find VS Code plug-in to install Code Runner Code Runner can run our files.

4 Variable constant naming rules

variable

Dart is a powerful scripting language that does not pre-define variable types and automatically pushes them down.

Dart can define variables through the var keyword and declare variables by type.

Var a int = 5; var a int = 5; An error.

var str = 'this is var';
String str = 'this is var';
int str = 123;
Copy the code

constant

Final and const modifiers

The const value doesn’t change and we have to assign it from the beginning.

Final can only be assigned once without starting; Not only does final have the property of a const compile-time constant, but most importantly it is a run-time constant, and final is lazy-initialized, that is, initialized before it is used for the first time at runtime.

The value of a variable that never changes is final or const rather than var or some other variable type.

final name = 'Bob'; // Without a type annotation
final String nickname = 'Bobby';
const bar = 1000000; // Unit of pressure (dynes/cm2)
const double atm = 1.01325 * bar; // Standard atmosphere
Copy the code

Naming rules

1. The variable name must consist of numbers, letters, underscores, and the dollar character ($).

2. Note that identifiers cannot start with a number

3. Identifiers cannot be reserved words and keywords.

4. Variable names are case sensitive. For example, age and age are different variables. In practical use, it is also recommended not to use a word case to distinguish between two variables.

5. Identifiers (variable names) must be given by name: nouns are recommended for variable names and verbs are recommended for method names.

5 Data Types

Common data types:

Numbers

Int must be an integer

A double can be either an integer or a floating point

Strings

String

Several ways to define a string

var str1 = 'this is str1'; var str2 = "this is str2"; String str1 = 'this is str1'; String str2 = "this is str2"; String str1 = "this is str1 this is str1 this is str1 this is str1"; String str = """ this is str1 this is str1 this is str1 """;Copy the code

Concatenation of strings

String str1 = 'Hello '; String str2 = 'Dart'; print("$str1 $str2"); print(str1 + str2); print(str1 +" "+ str2);Copy the code

Booleans (Boolean)

bool

List

In Dart, arrays are list objects, so most people just call them lists

List definition

var l1 = ['aaa','bbbb','cccc'];
var l2 = <String>[];
Copy the code

Maps

In general, a Map is a key-value pair dependent object. Keys and values can be objects of any type. Each key appears only once, while a value can appear multiple times

Map Definition

Var person = {" name ":" zhang ", "age" : 20, "work" : [" programmer ", "delivery"]}. print(person["name"]); var p = new Map(); P ["name"] = "name"; p["age"] = 22; P ["work"] = [" programmer "," delivery "]; print(p);Copy the code

Type judgment

var str=123; If (STR is String) {print(' is String '); } else if(str is int) { print('int'); } else {print(' other type '); }Copy the code

Operator conditions determine type conversions

Arithmetic operator

Add, subtract, multiply and divide, mod and round

int a = 13; int b = 5; print(a + b); // print(a-b); // print(a * b); // multiply print(a/b); // Print (a % b); // print(a ~/ b); / / integerCopy the code

++ —

The value increases and decreases by 1

So in an assignment if you have a plus plus — you write it first and then you do the assignment, if you have a plus plus — you write it first and then you do the assignment

var a = 10; var b = a--; print(a); //9 print(b); //10 var a = 10; var b = ++a; print(a); //11 print(b); / / 11Copy the code

Relational operator

int a = 5; int b = 3; print(a == b); Print (a! = b); Print (a > b); Print (a < b); Print (a >= b); Print (a <= b); // Check whether the value is less than or equal toCopy the code

Logical operator

! The not

bool flag = false; print(! flag);Copy the code

&& and: true if all are true and false otherwise

bool a = true;
bool b = true;
print(a && b);
Copy the code

| | or: the value to false words to false otherwise the value is true

bool a = false;
bool b = false;
print(a || b);
Copy the code

The assignment operator

The underlying assignment operator =?? =

int a = 10; int b = 3; print(a); int c = a + b; // from right to left int b; b ?? = 23; Print (b); print(b);Copy the code

Compound assignment operator += -= *= /= %= ~/=

var a = 13; a += 10; A = a + 10 print(a);Copy the code

Conditional expression

if else switch case

Var score = 41; var score = 60; If (score > 90) {print(' score '); } else if(score > 70) {print(' good '); } else if(score >= 60) {print(' score '); } else {print(' fail '); } var sex = "female "; Switch (sex) {case "male ": print(' male '); break; Case "female ": print(' female '); break; Default: print(' error '); break; }Copy the code

Ternary operator

bool flag = false; String c = flag ? 'I am true' :' I am false'; print(c);Copy the code

?? The operator

var a = 22;
var b = a ?? 10;
print(b);
Copy the code

Type conversion

Conversion between Number and String

Converts Number toString toString()

String类型转成Number类型 int.parse()

String str = '123'; var myNum = int.parse(str); print(myNum is int); String STR = '123.1'; var myNum = double.parse(str); print(myNum is double); // Error String price = ''; var myNum = double.parse(price); print(myNum); print(myNum is double); // try ... catch String price = ''; try { var myNum=double.parse(price); print(myNum); } catch(err) { print(0); } var myNum = 12; var str = myNum.toString(); print(str is String);Copy the code

Other types are converted to Booleans

IsEmpty: checks whether the string isEmpty

var str = ''; If (str.isEmpty) {print(' STR empty '); } else {print(' STR not empty '); } var myNum; if(myNum == 0) { print('0'); } else {print(' non-0 '); } var myNum; If (myNum == null) {print(' null '); } else {print(' not empty '); } var myNum = 0/0; print(myNum); if(myNum.isNaN) { print('NaN'); }Copy the code

7 Loop traversal

The for loop

The basic grammar

Int I = 1;

Step 2, judge I <=100

Print (I);

Step four, i++

Step 5 proceed from step 2 until the result is false

for (int i = 1; i <= 100; i++) { print(i); } / / print the List [' zhang ', 'bill', 'Cathy'] in the content of the var List = [' zhang ', 'bill', 'Cathy']. for(var i = 0; i < list.length; i++) { print(list[i]); }Copy the code

The while loop

Syntax format:

While (expression/loop condition){

}

do{

Statement/loop body

}while(expression/loop condition);

Note: 1. Don’t forget the last semicolon

2. Variables used in loop conditions need to be initialized

3, in the cycle body, there should be conditions to end the cycle, otherwise it will cause a dead cycle.

1 + 2 + 3 + 4 / / o... Sum of +100 int I = 1; var sum = 0; while(i <= 100) { sum += i; i++; } print(sum); int i = 1; var sum = 0; do{ sum += i; i++; }while(i <= 100); print(sum);Copy the code

Break and continue

Break statement function:

1. Make the process exit the switch structure in the switch statement.

2, in the loop statement to make the process out of the current loop, encounter a break loop terminates, the following code will not execute

Emphasize:

1. If a break statement has already been executed in the loop, the statement after break in the loop body is not executed.

2. In a multi-layer loop, a break statement can exit only one layer

Break can be used in switch cases and in for loops and while loops

The continue statement does the following:

[Note] Can only be used in a loop statement to make the loop end, that is, skip the statements under the weight of the loop that have not yet been executed, and then proceed to the next decision whether to execute the loop.

Continue can be used in both for and while loops, but it is not recommended for while loops as they may die if you are not careful

// Skip for(var I = 1; i <= 10; i++) { if(i == 4) { continue; /* Skip the current loop body and the loop will continue to execute */} print(I); } for(var I = 1; i <= 10; i++) { if(i == 4) { break; } print(I); }Copy the code

8 List

List of common attributes and methods:

Commonly used attributes

The length of the length

Reversed turning

IsEmpty whether isEmpty isEmpty

IsNotEmpty is not null

Var myList = [' myList ',' myList ']; print(myList.length); print(myList.isEmpty); print(myList.isNotEmpty); print(myList.reversed); // Sort the list backwards var newMyList = mylist.reversed. ToList (); print(newMyList);Copy the code

Commonly used method

Increase the add

AddAll concatenates an array

IndexOf looks for specific values passed in

Remove Deletes the specific value passed in

RemoveAt Removes the incoming index value

FillRange modify

insert(index,value); Insert at specified position

InsertAll (index,list) Specifies the position where the list is inserted

ToList () other types are converted toList

Join () List is converted to a string

The split() string is converted to a List

forEach

map

where

any

every

Var myList = [' banana ',' apple ',' watermelon ']; MyList. Add (' peach '); // Add a mylist. addAll([' peach ',' grape ']); Print (myList); Print (mylist.indexof (' apple ')); Mylist. remove(' watermelon '); myList.removeAt(1); print(myList); Var myList = [' myList ',' myList ']; myList.fillRange(1, 2, 'aaa'); // modify mylist.fillrange (1, 3, 'aaa'); myList.insert(1, 'aaa'); // insert a mylist.insertall (1, ['aaa', 'BBB ']); Print (myList); Var myList = [' myList ',' myList ']; var str = myList.join('-'); //list converts to string print(STR); print(str is String); //true var STR = 'banana - apple - watermelon '; var list = str.split('-'); print(list); print(list is List);Copy the code

9 Set

The main function of using it is to remove the duplicate contents of the array

A Set is an unordered and unrepeatable Set, so it cannot be indexed to get a value

var s = new Set(); S.a dd (" banana "); S.a dd (" apple "); S.a dd (" apple "); print(s); // {banana, apple} print(s.tolist ()); Var myList = [' banana ', 'apple', 'watermelon', 'banana', 'apple', 'banana', 'apple']. var s = new Set(); s.addAll(myList); print(s); print(s.toList());Copy the code

10 Map

A Map is an unordered key-value pair:

Commonly used attributes

Keys retrieves all key values

Values Gets all values

IsEmpty whether isEmpty isEmpty

IsNotEmpty is not null

Map person = {"name":" zhang3 ", "age":20}; var m = new Map(); M ["name"] = "name"; print(person); print(m); The Map person = {" name ":" zhang ", "age" : 20, "sex" : "male"}; print(person.keys.toList()); print(person.values.toList()); print(person.isEmpty); print(person.isNotEmpty);Copy the code

Commonly used method

Remove (key) Deletes the data of the specified key

addAll({… }) merge maps to add attributes to the map

ContainsValue Checks the value in the mapping and returns true/false

forEach

map

where

any

every

The Map person = {" name ":" zhang ", "age" : 20, "sex" : "male"}; Person. AddAll ({" work ": [' knock code ', 'delivery']," height ": 160}); print(person); person.remove("sex"); print(person); Print (person. ContainsValue (' zhang '));Copy the code

11 forEach map where any every

forEach

List myList = [' myList ', 'myList ']; for(var i = 0; i < myList.length; i++) { print(myList[i]); } for(var item in myList) { print(item); } myList.forEach((value) { print("$value"); }); var s = new Set(); S.a ddAll ([1222333]); s.forEach((value) => print(value)); Map person = {"name":" zhang3 ", "age":20}; person.forEach((key,value){ print("$key---$value"); });Copy the code

map

List myList = [1, 3, 4];      
var newList = myList.map((value) {
     return value * 2;
});
print(newList.toList());
Copy the code

where

List myList = [1, 3, 4, 5, 7, 8, 9];
var newList = myList.where((value) {
     return value > 5;
});
print(newList.toList());
Copy the code

any

List myList = [1, 3, 4, 5, 7, 8, 9]; Var f = myList. Any ((value) {return value > 5; }); print(f);Copy the code

every

List myList = [1, 3, 4, 5, 7, 8, 9]; Var f = myList. Every ((value) {// return value > 5; }); print(f);Copy the code

Method definition Variable method scope

Built-in methods/functions

print();

Custom methods

The basic format of a custom method:

Return type method name (parameter 1, parameter 2…) {

Method body

Return Return value;

}

Void printInfo(){print(' I am a custom method '); } int getNum(){ var myNum = 123; return myNum; } String printUserInfo(){ return 'this is str'; } List getList(){ return ['111','2222','333']; } void main(){print(' call system built-in method '); printInfo(); var n = getNum(); print(n); print(printUserInfo()); print(getList()); print(getList()); Void XXX (){aaa(){print(getList()); print('aaa'); } aaa(); } // aaa(); Error: XXX (); // Call method}Copy the code

13 Method parameters, optional parameters, default parameters, named parameters, and method as parameters

Methods the reference

// Define a method to find the sum of all numbers from 1 to 60 1+2+3+... +60 int sumNum(int n){ var sum=0; for(var i = 1; i <= n; i++){ sum+=i; } return sum; } var n1 = sumNum(5); print(n1); var n2 = sumNum(100); print(n2); String printUserInfo(String username, int age){// return "Name :$username-- age :$age"; } print(printUserInfo); / / argumentsCopy the code

Optional parameters

String printUserInfo(String username, [int age]){// line argument if(age! = null){return "name :$username-- $age"; } return "name :$username-- age secret "; } print(printUserInfo(' printUserInfo ', 21); Print (printUserInfo(' printUserInfo '));Copy the code

The default parameters

String printUserInfo(String username, [String sex = 'male ', int age]){// if(age! = null) {return "name: $username - gender: $sex - age: $age"; } return "name :$username-- gender :$sex-- age secret "; } print(printUserInfo); Print (printUserInfo); print(printUserInfo); Print (printUserInfo(' l ', 'l ', 30));Copy the code

Named parameters

String printUserInfo(String username, {int age, String sex = 'male '}){// if(age! = null) {return "name: $username - gender: $sex - age: $age"; } return "name :$username-- gender :$sex-- age secret "; } print(printUserInfo(age:20, sex:' unknown ');Copy the code

Method as parameter

Var fn = () {print(' I am an anonymous method '); }; fn(); Fn1 (){print('fn1'); } // method fn2(fn){fn(); } // call fn2 and pass fn1 as an argument to fn2(fn1);Copy the code

14 Arrow function The function calls each other

Arrow function

*/ List List = [' apple ', 'banana ',' watermelon ']; */ List List = [' apple ', 'banana ',' watermelon ']; list.forEach((value){ print(value); }); list.forEach((value) => print(value)); list.forEach((value) => { print(value) }); List = [4, 1, 2, 3, 4]; /* List = [4, 1, 2, 3, 4]; var newList = list.map((value){ if(value > 2){ return value * 2; } return value; }); print(newList.toList()); var newList = list.map((value) => value > 2 ? value * 2 : value); print(newList.toList());Copy the code

Function calls to each other

/ * requirements: Bool isEvenNumber(int n){if(n) bool isEvenNumber(int n){if(n) bool isEvenNumber(int n){if(n) bool isEvenNumber(int n){if(n % 2 == 0){ return true; } return false; } printNum(int n){ for(var i = 1; i <= n; i++){ if(isEvenNumber(i)){ print(i); } } } printNum(10);Copy the code

15 closure

1, global variable features: global variable resident memory, global variable pollution global

2, the characteristics of local variables: non-resident memory will be garbage recycling mechanism, will not pollute the global

Want to achieve the following functions: 1. Resident memory 2. No global pollution

Closures are generated, and closures solve this problem…..

Closure: function nested functions, internal functions call variables or arguments of external functions, and the variables or arguments are not reclaimed by the system (without freeing memory)

A closure is a function that nested a function and returns the function inside it.

Var a = 123; void main(){ print(a); fn(){ a++; print(a); } fn(); fn(); fn(); PrintInfo (){var myNum = 123; myNum++; print(myNum); } printInfo(); printInfo(); printInfo(); Var a = 123; /* does not pollute global resident memory */ return(){a++; print(a); }; } var b = fn(); b(); b(); b(); }Copy the code

Introduction to object-oriented and built-in objects

There are three basic features of object-oriented programming (OOP)

encapsulation

Encapsulation is a major feature of object and class concepts. Encapsulate, encapsulate objective things into abstract classes, and provide part of their attributes and methods to other objects to call, and part of the attributes and methods are hidden.

inheritance

One of the main features of object-oriented programming (OOP) languages is inheritance. Inheritance is the ability to take the functionality of an existing class and extend it without having to rewrite the original class.

polymorphism

It is possible to assign a pointer of a subclass type to a pointer of a superclass type. The same function call may have different execution effects.

Everything in Dart is an Object, and all objects inherit from the Object class.

Dart is an object-oriented language that uses classes and single inheritance. All objects are instances of classes, and all classes are subclasses of Object

A class usually consists of attributes and methods.

List list = new List(); list.isEmpty; List. The add (" banana "); List. The add (' 1 'banana); Map m = new Map(); M ["username"] = "username"; m.addAll({"age":20}); m.isEmpty; Object a = 123; Object v = true; print(a); print(v);Copy the code

17 Creating a custom class Using a class

Dart is an object-oriented language that uses classes and single inheritance. All objects are instances of classes, and all classes are subclasses of Object

Class Person {String name = "Person "; int age = 23; void getInfo(){ // print("$name----$age"); print("${this.name}----${this.age}"); } void setInfo(int age){ this.age = age; }} void main(){p1 = new Person(); print(p1.name); p1.setInfo(28); p1.getInfo(); }Copy the code

The default constructor for a custom class

Class Person {String name = 'Person '; int age = 20; // The default constructor Person(){print(' This is what's inside the constructor and this method fires on instantiation '); } void printInfo(){ print("${this.name}----${this.age}"); }} // class Person {String name; int age; Person(String name, int age){this.name = name; this.age = age; } void printInfo(){ print("${this.name}----${this.age}"); } } class Person { String name; int age; Person(this.name, this.age); void printInfo(){ print("${this.name}----${this.age}"); }} void main(){Person p1 = new Person(' Person ',20); p1.printInfo(); Person p2 = new Person(' 1 ',25); p2.printInfo(); }Copy the code

A named constructor for a custom class

Dart can write multiple constructors

class Person { String name; int age; Person(this.name, this.age); Person.now(){print(' I'm a named constructor '); } Person.setInfo(String name, int age){ this.name = name; this.age = age; } void printInfo(){ print("${this.name}----${this.age}"); } } void main(){ var d = new DateTime.now(); // Call the named constructor print(d); Person p1 = new Person(' Person ', 20); Person p1 = new person.now (); Person p1 = new person.now (); // Name the constructor Person p1 = new person.setinfo (' lisi ',30); p1.printInfo(); }Copy the code

Separate the class into a module

Dart import 'lib/ person. dart'; Void main(){Person p1 = new person.setinfo (' 1', 30); p1.printInfo(); }Copy the code

Private methods and private properties

Unlike other object-oriented languages, Dart does not have the public private protected access modifier in Data

We can use _ to make an attribute or method private.

class Animal { String _name; // Private attribute int age; // Short for the default constructor Animal(this._name, this.age); void printInfo(){ print("${this._name}----${this.age}"); } String getName(){ return this._name; } void _run(){print(' this is a private method '); } execRun(){ this._run(); }} import 'lib/ animal.dart '; Void main(){Animal a = new Animal(' puppy ', 3); print(a.getName()); a.execRun(); // Call private methods indirectly}Copy the code

The use of getter and setter modifiers in a class

class Rect { int height; int width; getArea(){ return this.height * this.width; } } class Rect { num height; num width; Rect(this.height, this.width); area(){ return this.height * this.width; } } void main(){ Rect r = new Rect(10, 4); Print (" area: ${state Richard armitage rea ()} "); } class Rect { num height; num width; Rect(this.height, this.width); get area{ return this.height * this.width; } } void main(){ Rect r = new Rect(10, 2); Print (" area: ${state Richard armitage rea} "); Area} class Rect {num height; num width; Rect(this.height, this.width); get area{ return this.height * this.width; } set areaHeight(value){ this.height = value; } } void main(){ Rect r = new Rect(10, 4); Print (${r.rea ()}"); r.areaHeight = 6; print(r.area); }Copy the code

Class initializers

We can also initialize instance variables before the constructor body is run

class Rect {
  int height;
  int width;
  Rect():height = 2, width = 10{
    print("${this.height}---${this.width}");
  }
  getArea(){
    return this.height * this.width;
  } 
}

void main(){
  Rect r = new Rect();
  print(r.getArea()); 
}
Copy the code

Class static member static method

Static members in Dart:

1. Use the static keyword to implement class-level variables and functions

2. Static methods cannot access non-static members. Non-static methods can access static members

Class Person {static String name = 'Person '; static void show() { print(name); } } main(){ print(Person.name); Person.show(); } class Person {static String name = 'Person '; int age = 20; static void show() { print(name); } void printInfo(){/* Non-static methods can access static members as well as non-static members */ print(name); Print (this.age); // Access the non-static property show(); Static void printUserInfo(){// Static void printUserInfo(); // static attribute show(); // static method // print(this.age); // static methods cannot access non-static attributes // this.printinfo (); // static methods cannot access non-static methods // printInfo(); } } main(){ print(Person.name); Person.show(); Person p = new Person(); p.printInfo(); Person.printUserInfo(); }Copy the code

Object operator

? Conditional operators (Understanding)

As type Conversion

Is Type Judgment

. Cascading operations (concatenation) (remember)

class Person { String name; num age; Person(this.name, this.age); void printInfo() { print("${this.name}---${this.age}"); } } main(){ Person p; p? .printInfo(); Person p = new Person(' Person ', 20); p? .printInfo(); Person p = new Person(' Person ', 20); If (p is Person){p.name = "Person "; } p.printInfo(); print(p is Object); var p1; p1 = ''; P1 = new Person(' 1', 20); // // p1.printInfo(); // (p1 as Person).printInfo(); Person p1 = new Person(' 1', 20); p1.printInfo(); P1. Name = 'zhangsan 222'; p1.age = 40; p1.printInfo(); Person p1 = new Person(' 1', 20); p1.printInfo(); p1.. Name = "li Si".. age = 30 .. printInfo(); }Copy the code

Class inheritance – Simple inheritance

1. Subclasses inherit from their parent class using the extends keyword

Subclasses inherit properties and methods visible from their parent class, but not constructors

3. Subclasses can override getters and setters for the methods of their parent class

Class Person {String name = 'Person '; num age = 20; void printInfo() { print("${this.name}---${this.age}"); } } class Web extends Person { } main(){ Web w = new Web(); print(w.name); w.printInfo(); }Copy the code

Use of the super keyword

class Person { String name; num age; Person(this.name, this.age); void printInfo() { print("${this.name}---${this.age}"); } } class Web extends Person { Web(String name, num age) : Super (name, age){}} main(){Person p = new Person('李四', 20); p.printInfo(); Person p1 = new Person(' Person ', 20); p1.printInfo(); Web w = new Web(' zhang SAN ', 12); w.printInfo(); }Copy the code

Instantiate the self class to pass parameters to the parent class constructor

class Person { String name; num age; Person(this.name, this.age); Person.xxx(this.name, this.age); void printInfo() { print("${this.name}---${this.age}"); } } class Web extends Person { String sex; Web(String name, num age, String sex) : super.xxx(name, age){ this.sex = sex; } run(){ print("${this.name}---${this.age}--${this.sex}"); }} main(){Person p = new Person(' Person ', 20); p.printInfo(); Person p1 = new Person(' Person ', 20); p1.printInfo(); Web w = new Web(' zhang SAN ', 12, "male "); w.printInfo(); w.run(); }Copy the code

Instantiate the self-class to pass parameters to the named constructor

class Person { String name; num age; Person(this.name, this.age); Person.xxx(this.name, this.age); void printInfo() { print("${this.name}---${this.age}"); } } class Web extends Person { String sex; Web(String name, num age, String sex) : super.xxx(name, age){ this.sex = sex; } run(){ print("${this.name}---${this.age}--${this.sex}"); }} main(){Person p = new Person(' Person ', 20); p.printInfo(); Person p1 = new Person(' Person ', 20); p1.printInfo(); Web w = new Web(' zhang SAN ', 12, "male "); w.printInfo(); w.run(); }Copy the code

A method that overrides the parent class

class Person { String name; num age; Person(this.name, this.age); void printInfo() { print("${this.name}---${this.age}"); } work(){print("${this.name} work..." ); } } class Web extends Person { Web(String name, num age) : super(name, age); run(){ print('run'); Void printInfo(){print(" name: ${this.name}-- age: ${this.age}"); } @override work(){print("${this.name} work is writing code "); }} main(){Web w = new Web(' li si ', 20); w.printInfo(); w.work(); }Copy the code

Call a method from a parent class

class Person { String name; num age; Person(this.name, this.age); void printInfo() { print("${this.name}---${this.age}"); } work(){print("${this.name} work..." ); } } class Web extends Person { Web(String name, num age) : super(name, age); run(){ print('run'); super.work(); / / the class call the superclass method @} / / overwrite the superclass method can override / / write also can not write advice when override a superclass method combined with @ override void printInfo () {print (" name: ${this. The name} - age: ${this.age}"); }} main(){Web w = new Web(' li si ', 20); w.printInfo(); w.run(); }Copy the code

An abstract class

Abstract classes are used to define standards, and subclasses can inherit abstract classes or implement abstract class interfaces.

1. Abstract classes are defined by the abstract keyword

Abstract methods cannot be declared with abstract. Methods without a method body are called abstract methods.

If a subclass inherits an abstract class, it must implement its abstract methods

If you use an abstract class as an interface implementation, you must implement all properties and methods defined in the abstract class.

5. An abstract class cannot be instantiated, only subclasses that inherit it can

The difference between extends and implements:

1. Extends extends an abstract class if we want to reuse methods from an abstract class and constrain our classes with abstract methods

2. Implements abstract classes, if only as a standard

Example: Defining an Animal class requires that its subclasses contain the eat method

abstract class Animal { eat(); // Abstract method run(); PrintInfo (){print(' I am an ordinary method in an abstract class '); }} class Dog extends Animal {@override eat() {print(' Dog is eating a bone '); } @override run() {print(' the dog is running '); }} class Cat extends Animal {@override eat() {print(' Cat is eating a mouse '); } @override run() {print(' the cat is running '); } } main(){ Dog d = new Dog(); d.eat(); d.printInfo(); Cat c = new Cat(); c.eat(); c.printInfo(); // Animal a=new Animal(); // Abstract classes cannot be instantiated directly}Copy the code

18 polymorphic

It is possible to assign a pointer of a subclass type to a pointer of a superclass type. The same function call may have different execution effects.

An instance of a subclass is assigned to a reference to the parent class.

Polymorphism is when a parent class defines a method and does not implement it, leaving it to its subclasses, each of which behaves differently.

abstract class Animal { eat(); } class Dog extends Animal {@override eat() {print(' Dog is eating a bone '); } run(){ print('run'); }} class Cat extends Animal {@override eat() {print(' Cat is eating a mouse '); } run(){ print('run'); } } main(){ Dog d = new Dog(); d.eat(); d.run(); Cat c = new Cat(); c.eat(); Animal d = new Dog(); d.eat(); Animal c = new Cat(); c.eat(); }Copy the code

19 interface

Like Java, DART has interfaces, but there are differences.

First, the DART interface does not have the interface keyword to define the interface. Instead, ordinary or abstract classes can be implemented as interfaces.

The implements keyword is also used.

Dart’s interface is a bit strange, however. If you implement a generic class, you’ll need to overwrite all the properties and methods in the generic class and abstraction.

And because abstract classes can define abstract methods that ordinary classes can’t, it’s common to use abstract classes if you want to implement things like Java interfaces.

It is recommended to define interfaces using abstract classes.

Define a DB library to support mysql MSSQL mongodb

Mysql MSSQL mongodb classes have the same method

Abstract class Db {// as an interface interface: conventions, specifications, String uri; // Add (String data); save(); delete(); } class Mysql implements Db { @override String uri; Mysql(this.uri); @override add(data) {print(' this is mysql add method '+data); } @override delete() { return null; } @override save() { return null; } remove() { } } class MsSql implements Db { @override String uri; @override add(String data) {print(' this is MSSQL add method '+data); } @override delete() { return null; } @override save() { return null; } } main() { Mysql mysql = new Mysql('xxxxxx'); mysql.add('1243214'); }Copy the code

20 implements multiple interfaces

abstract class A {
  String name;
  printA();
}

abstract class B {
  printB();
}

class C implements A, B {  
  @override
  String name; 
  
  @override
  printA() {
    print('printA');
  }
  
  @override
  printB() {
    return null;
  }
}

void main(){
  C c = new C();
  c.printA();
}
Copy the code

21 mixins

Mixins, which means to mixin other functions into a class.

Mixins can be used to achieve something like multiple inheritance

Because the conditions for mixins change with Dart releases, here are the conditions for using mixins in DART2.x:

A mixins class can only inherit from Object, not other classes

2. Classes that are mixins cannot have constructors

A class can mixins multiple mixins classes

Mixins are not inheritance, nor are they interfaces, but rather a completely new feature

class A { String info = "this is A"; void printA() { print("A"); } } class B { void printB() { print("B"); } } class C with A, B { } void main() { var c = new C(); c.printA(); c.printB(); print(c.info); } class Person { String name; num age; Person(this.name, this.age); printInfo() { print('${this.name}----${this.age}'); } void run() { print("Person Run"); } } class A { String info = "this is A"; void printA() { print("A"); } void run() { print("A Run"); } } class B { void printB() { print("B"); } void run() { print("B Run"); } } class C extends Person with B, A { C(String name, num age) : super(name, age); } void main() {var c = new c (' c ', 20); c.printInfo(); c.printB(); print(c.info); c.run(); }Copy the code

What is the instance type of mixins?

Quite simply, the type of a mixins is a subtype of its superclass.

class A {
  String info = "this is A";
  void printA() {
    print("A");
  }
}

class B {
  void printB() {
    print("B");
  }
}

class C with A, B {
  
}

void main() {  
  var c = new C();  
  print(c is C);    //true
  print(c is A);    //true
  print(c is B);    //true
  
  var a = new A();
  print(a is Object);
}
Copy the code

22 generic

Generics address the reuse of class interface methods and support for non-specific data types (type validation)

Generic method

String getData(string value) {return value; } // Both string and int are supported (code redundancy) string getData1(string value) {return value; } int getData2(int value) { return value; GetData (value) {return value; getData(value) {return value; } // Not specifying a type abandons type checking. What we want to implement now is to return what is passed in. GetData <T>(T value) {return value; getData<T>(T value) {return value; } void main() { print(getData(21)); print(getData('xxx')); GetData < String > (' hello '); print(getData<int>(12)); }Copy the code

The use of the collection List generic class

Example: To convert the following class to a generic class, add int and String to the List. But the type increment must be consistent with each call

class PrintClass<T> { List list = new List<T>(); void add(T value){ this.list.add(value); } void printInfo() { for(var i = 0; i < this.list.length; i++) { print(this.list[i]); } } } main() { PrintClass p = new PrintClass<int>(); p.add(12); p.add(23); p.printInfo(); List list=new List<String>(); // // list.add(12); List.add (' hello '); List. The add (' hello 1 '); print(list); List list=new List<int>(); // // list.add(" Hello "); List.add (12); print(list); }Copy the code

A generic interface

Data cache functions: file cache, and memory cache. Memory and file caching are implemented according to interface constraints.

1, define a generic interface constraint that subclasses that implement it must have getByKey(key) and setByKey(key,value)

SetByKey = setByKey (); setByKey = setByKey ()

abstract class Cache<T> { getByKey(String key); void setByKey(String key, T value); } class FlieCache<T> implements Cache<T> { @override getByKey(String key) { return null; } @override void setByKey(String key, T value) {print(key=${key} value=${value}); } } class MemoryCache<T> implements Cache<T> { @override getByKey(String key) { return null; } @override void setByKey(String key, T value) {print(key=${key} value=${value} -); } } void main(){ MemoryCache m = new MemoryCache<String>(); M.setbykey ('index', 'home data '); MemoryCache m = new MemoryCache<Map>(); M.setbykey ('index', {"name":" zhang ", "age":20}); }Copy the code

23 libraries

The Dart basics were mostly written in a file, but that’s not possible in real development. Modularity is important, so the concept of a library is used.

In Dart, the use of libraries is introduced through the import keyword.

The Library directive creates a library, and each Dart file is a library, even if it is not specified using the Library directive.

There are three main types of libraries in Dart

1. Our custom library

import ‘lib/xxx.dart’;

2. System built-in library

import ‘dart:math’;

import ‘dart:io’;

import ‘dart:convert’;

3. Library in Pub package management system

pub.dev/packages

pub.flutter-io.cn/packages

pub.dartlang.org/flutter/

1. Create a new pubspec.yaml in your project root directory

2. In the pubspec.yaml file, configure the name, description, dependencies, etc

3. Then run pub get to get the package and download it locally

Import ‘package: HTTP /http.dart’ as HTTP; See the document and use it

Import your own local library

import 'lib/Animal.dart'; Main () {var a = new Animal(' black dog ', 20); print(a.getName()); }Copy the code

Import the system built-in library

import 'dart:io'; import 'dart:convert'; void main() async { var result = await getDataFromZhihuAPI(); print(result); } // API interface: http://news-at.zhihu.com/api/3/stories/latest getDataFromZhihuAPI () is async {/ / 1, create var HttpClient = new HttpClient object HttpClient(); Var Uri = new uri. HTTP ('news-at.zhihu.com','/ API /3/stories/latest'); Var request = await httpClient.getUrl(uri); Var response = await request.close(); Transform (utf8.decoder).join(); return await response.transform(utf8.decoder).join(); }Copy the code

Async and await

There are only two things to remember when using these two keywords:

Only async methods can call methods using the await keyword

The await keyword must be used if other async methods are called

Async is making methods asynchronous.

Await is waiting for an asynchronous method to complete.

void main() async { var result = await testAsync(); print(result); } // Async() async{return 'Hello async'; }Copy the code

Import the library in the Pub package management system

Pub package management system:

1. Find the library from the following url

pub.dev/packages

pub.flutter-io.cn/packages

pub.dartlang.org/flutter/

2. Create a pubspec.yaml file with the following contents

Name: XXX description: A new flutter module project. dependencies: HTTP: ^0.12.0+2 date_format: ^1.0.6Copy the code

3. Configure dependencies

4. Run pub get to obtain the remote library

5, see the document into the library use

import 'dart:convert' as convert;
import 'package:http/http.dart' as http;
import 'package:date_format/date_format.dart';

main() async {
  var url = "http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20&page=1";
  
  // Await the http get response, then decode the json-formatted responce.
  var response = await http.get(url);
  if (response.statusCode == 200) {
    var jsonResponse = convert.jsonDecode(response.body);
    print(jsonResponse);
  } else {
    print("Request failed with status: ${response.statusCode}.");
  }
  print(formatDate(DateTime(1989, 2, 21), [yyyy, '*', mm, '*', dd]));
}
Copy the code

Library rename conflict resolved

Conflict resolution

When importing identifiers with the same name in two libraries, it is common for Java to specify which identifiers to use by writing the full package name path, even without import, which is mandatory in Dart. When conflicts occur, the AS keyword can be used to specify the library prefix. See the following example:

import 'package:lib1/lib1.dart'; import 'package:lib2/lib2.dart' as lib2; Element element1 = new Element(); // Uses Element from lib1. lib2.Element element2 = new lib2.Element(); // Uses Element from lib2. import 'lib/Person1.dart'; import 'lib/Person2.dart' as lib; Main (List<String> args) {Person p1 = new Person(' 3 ', 20); p1.printInfo(); Lib. Person p2 = new lib.Person(' lib. ', 20); p2.printInfo(); }Copy the code

Part of the import

If only part of the library needs to be imported, there are two modes:

Mode 1: Import only the required parts, using the show keyword, as shown in the following example:

import 'package:lib1/lib1.dart' show foo;
Copy the code

Pattern 2: Hide unwanted parts using the hide keyword, as shown in the following example:

import 'package:lib2/lib2.dart' hide foo; 
Copy the code
//import 'lib/myMath.dart' show getAge;
import 'lib/myMath.dart' hide getName;

void main(){
//  getName();
  getAge();
}
Copy the code

Lazy loading

Also known as lazy loading, it can be loaded as needed.

The biggest benefit of lazy loading is that it reduces APP startup time.

Lazy loading is specified using the Deferred as keyword, as shown in the following example:

When needed, use the loadLibrary() method to load:

import 'package:deferred/hello.dart' deferred as hello;
greet() async {
  await hello.loadLibrary();
  hello.printGreeting();
}
Copy the code