1. Variable declaration and naming rules

1, the introduction of

Dart begins because I saw flutter. All of this is a no-brainer for someone who knows javaScript and Java. I like to take notes when I study so I write down some of these things.

Dart doesn’t take time at all if you know some languages.

2, the statement

Dart is a powerful scripting language that allows variable types to be defined without default

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

Such as:

var str = 'this is var';String str = 'this is var';
int str = 123
Copy the code
void main() {
    var str = 'hello dart';
    var numx = 1234;
    print(str);
    print(numx);
    
    String str1 = 'hello dart';
    print(str);
    
    int numx1 = 123;
    print(numx1);
}
Copy the code

Definition error:

var str = ' ';
str = 1234; // error A value of type 'int' can't be assigned to A variable of type 'String'
print(STR);Copy the code
 String str = 12312;// error A value of type 'int' can't be assigned to A variable of type 'String'
Copy the code

3. Naming rules

Dart Naming Rules:

1. The variable name must contain numbers, letters, underscores, and dollar signs ($)

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. It is also recommended not to use one in practical applications

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

Dart constants: final and const modifiers

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

Final can start without assignment but can only be assigned once; Final is not only a compile-time constant that is const, but most importantly a run-time constant, and final is lazy-initialized, that is, initialized before it is used for the first time at run time. See the example below for defining time.

An immutable quantity, such as PI = 3.1415926, is final or const instead of var or some other variable type

 final name = "Bob";
 final String strname = "Bobby";

 const bar = 1000000;
 const double a = 1.123 * bar;

 final date1 = new DateTime.now();
 const date2 = new DateTime().now();// New expression is not a constant expression.
Copy the code

2. Dart data type

Dart supports the following data types:

I. Common data types:

Numbers: int, double

String (String) : String

Booleans (Boolean) : bool

Lists: In Dart, arrays are List objects, so most people just call them lists

Maps: In general, a Map is an object associated with key-value pairs. Keys and values can be objects of any type. Each key

1. Number type

Int must be an integer

A double can be either an integer or a floating point

2. String

String definition “” “single quote definition will hold the format

  String str1 = '111';
  String str2 = "222";
  String str3 = "' 111 111 ' ' ';

  print(str1);
  print(str2);
  print(str3);
Copy the code

Running results:

String Indicates the concatenation of strings

  String str1 = 'hello';
  String str2 = "Dart";

  print("$str1 $str2");
  print(str1 + str2);
Copy the code

Boolean type

  bool flag = true;
  print(flag);
Copy the code

4, List (array/collection)

var l1 = ['aaa'.'bbb'.'ccc'];
print(l1);
print(l1.length);
print(l1[0]);
/ / output:
//[aaa, bbb, ccc]
/ / 3
//aaa

var l2 = new List(a); l2.add("111");
l2.add("222");
l2.add("333");
print(l2);
// Output: [111, 222, 333]

// Define list to specify the type
var l3  = List<String> (); l3.add("111");
l3.add(222);Error: The argument type 'int' can't be assigned to The parameter type 'String'.
print(l3);
Copy the code

5. Maps

// Key must be marked"
var person = {
  "name" : "Zhang"."age" : 20."like" : ["111"."222"]};print(person);
{name: zhang3, age: 20, like: [111, 222]}
print(person["name"]);
// Output: zhang SAN

var p = new Map(a); p["name"] = "Zhang";
p["age"] = 20;
p["like"] = ["111"."222"];

print(p);
{name: zhang3, age: 20, like: [111, 222]}
Copy the code

Data types rarely used:

Runes: Rune is a string encoded in UTF-32. It can be converted from text to emoticons or to represent specific words.

  var clapping = '\u{1f44f}';
  print(clapping);
  print(clapping.codeUnits);
  print(clapping.runes.toList());

  Runes input = new Runes('\u2665 \u{1f605} \u{1f60e} \u{1f47b} \u{1f596} \u{1f44d}');

  print(new String.fromCharCodes(input));
Copy the code

Symbols: Symbol objects represent operators or identifiers declared in the Dart program.

Judge the data type

The is keyword determines the data type

var str = '1234';

if(str is String) {print('Is of type String');
}else {
  print('other');
}
// Output: String
Copy the code

Dart arithmetic operator/conditional expression/type conversion

1. Operators

1. Arithmetic operators

+ - * / ~/(rounded) %Copy the code

2. Relational operators

= =! = > < >= <=Copy the code

3. Logical operators

! && | |Copy the code

4. Assignment operators

The underlying assignment operator =?? = Compound assignment operator += -= *= /= %= ~/=Copy the code
int b =10; b?? =23;
print(b);// Output: 10

intb ; b?? =23;
print(b);// Output: 23

/ / the above?? = indicates that assignment is performed only if b is empty
Copy the code

2. Conditional expressions

1, If else switch case

2. The ternary operator

bool flag = true;
String c = flag? 'true':'false';
print(c);/ / output true

Copy the code

3,?? The operator

var a ;
var b = a ?? 10;
print(b);/ / output 10

var a = 7 ;
var b = a ?? 10;
print(b);/ / output 7

Copy the code

3. Type conversion

1. Conversion between number and String

Converts number toString toString()

String is converted to number parse

String str = '123';
var numx = int.parse(str);
print(numx is int);/ / output true
Copy the code

2. Other types are converted to Booleans

Dart loop statement

1, For basic grammar

for(int i = 1 ; i <= 100; i++){print(i);
}
Copy the code

2, while the do… while

int  i = 1;
while(i <= 10) {print(i);
  i++;
}

do{
  print("Always do it once.");

}while(i < 2);
Copy the code

3, the continue/break

Continue: Terminates the loop, but continues the current loop.

Break: Jumps out of the current loop body, ending the current loop, but only one level out.

Dart Set type List/Set/Map

1, the List

1. Common attributes

Reversed (reversed), isEmpty (reversed), isNotEmpty (reversed)

2. Common methods

Add (add), addAll (join array), indexOf (search, pass the value), remove (delete, pass the value), removeAt (delete, Insert (index,value) insert(index,value) insert(index, list) insert list (index,list) insert list (toList) (other types converted toList) join (list converted to string) spli T (string to List)

2, the Set

A set is an unordered and unrepeatable set.

3, the Map

1. Common attributes

Keys: retrieves all key values; values: retrieves all values; isEmpty: whether the value isEmpty; isNotEmpty: whether the value isNotEmpty

2. Common methods

Remove (key) : deletes the data of the specified key. AddAll ({… }) : merge the mapping, add attributes to the mapping, containsValues: check the value of the mapping, return true/false

ForEach map where any every

  List myList = ["111"."222"."333"];
  myList.forEach((value) {
    print(value);
  });
/ / output:
/ / 111
/ / 222
/ / 333
  List myListnumx = [1.2.3.4];

  var newList = myListnumx.map((e) {
    return e * 2;
  });
  print(newList);/ / (2, 4, 6, 8)

  var newListWhere = myListnumx.where((e) {
    return e > 2;
  });
  print(newListWhere);/ / (3, 4)

  // Return true as long as one condition is met
  var f = newList.any((element) {
    return element > 2;
  });
  print(f);//true

  // All satisfy return true
  var d = newList.every((element) {
    return element > 2;
  });
  print(d);//false
Copy the code

Functions in Dart

1. Definition of functions

void main(List<String> args) {
  var n = getnumx();
  print(n);/ / 123
  printInfo();// Custom methods!
}

void printInfo() {
  print("Custom methods!");
}
int getnumx() {
  return 123;
}
Copy the code
void main(List<String> args) {
  print(sum(1.2));/ / 3
  print(sumd(1.2));/ / 3
}

int sum(int a,int b){
  return a+b;
}

int sumd(a,b){
  return a+b;
}
Copy the code

2. Optional parameters

void main(List<String> args) {
  print(getStr("xxx"));//xxx
  print(getStr("xxx".12));//xxx 12
}

String getStr(String name,[int age]){
  if(age ! =null) {return "$name   $age";
  }else {
    returnname; }}Copy the code

3. Default parameters

void main(List<String> args) {
  print(getStr("xxx"));/ / XXX
  print(getStr("xxx"."Female".20));/ / XXX 20 female
 
}

String getStr(String name,[String sex = 'male'.int age]){
  if(age ! =null) {return "$name   $age   $sex";
  }else {
    return "$name   $sex"; }}Copy the code

4. Named parameters

Note: Pass parameters are defined in the same way as key in {}.

void main(List<String> args) {
  print(getStr("xxx"));/ / XXX
  print(getStr("xxx",sex:"Female",age:20));/ / XXX 20 female
 
}

String getStr(String name,{String sex = 'male'.int age}){
  if(age ! =null) {return "$name   $age   $sex";
  }else {
    return "$name   $sex"; }}Copy the code

Arrow function

main(List<String> args) {
  List list = ["111"."222"."333"];

  list.forEach((element) => {
    print(element)  // There is no mark in it, only one line
  });
}
Copy the code

6. Anonymous functions

main(List<String> args) {
   //fun is anonymous
   var fun = (){
    print("xxxx");
  };
  fun(); 
}
Copy the code

7. Self-execution method

main(List<String> args) {
  ((){
    print("Self-executing method!"); }) (); }Copy the code

8. Recursion of methods

main(List<String> args) {
  var sum =1;
  fn(n) {
    sum+=n;
    if(n==0) {return;
    }
    fn(n- 1);
  }
  fn(100);
  print(sum);
}
Copy the code

9, closures

Global variables: global variables reside in memory, global variables pollute the world

Local variables: non-resident memory is collected by the garbage collection mechanism without global contamination

Closure implementation: resident in memory but does not pollute globally

In plain English, closures are functions that nest functions and return functions inside them.

main(List<String> args) {
  fn(){
    var a = 1;
    return (){
      a++;
      print(a);
    };
  }
  var b = fn();
  b();/ / 2
  b();/ / 3
  b();/ / 4
}
Copy the code

7. Objects in Dart

1. Introduction to Object Orientation

Object-oriented programming (OOP) is characterized by encapsulation, inheritance, and polymorphism

Encapsulation: Encapsulation is the main characteristic of object and class concepts. Encapsulate, encapsulate objective things into abstract classes, and provide some of their properties and methods to other objects.

Inheritance: One of the main features of object-oriented programming languages is inheritance. Inheritance can be described as a capability, but inheritance is actually to improve the reuse and extensibility of code. Inheritance is the technique of using the definition of an existing class as a basis to create a new class. The definition of a new class can add new data or new functions, or use the functions of the parent class, but can not selectively inherit the parent class.

Polymorphism: Allows assigning a pointer of a subtype to a pointer of a parent type. The same function call may have different execution effects.

Dart is no exception. Everything 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.

2. Class creation

class Person{
  String name = "cdx";
  int age = 23;

  void getInfo(){
    print("The ${this.name}  The ${this.age}");
    print(this.name + ""+ this.age.toString());
  }

  void setInfo(age){
    this.age = age;
  }
}

main(List<String> args) {
  var p1 = new Person();
  print(p1.age); / / 23
  p1.getInfo();//cdx 23 cdx 23
  p1.setInfo(18);
  print(p1.age);/ / 18
}
Copy the code

constructors

class Person{
  String name = "cdx";
  int age = 23;
  // Default constructor
  Person(){
    print("Constructor");
  }

  void getInfo(){
    print("The ${this.name}  The ${this.age}");
  }
}

main(List<String> args) {
  var p1 = new Person();
}
// Output: constructor
Copy the code
class Person{
  String name = "cdx";
  int age = 23;

  Person(String name , int age){
    this.name = name;
    this.age = age;
  }
  // Short form
  // Person(this.name,this.age);

  void getInfo(){
    print("The ${this.name}  The ${this.age}");
  }
}

main(List<String> args) {
  var p1 = new Person("zs".12);
  p1.getInfo();//zs 12

  var p2 = new Person("ls".16);
  p2.getInfo();//ls 16
}
Copy the code

Note: Only one constructor can be defined by default.

4. Name the constructor

The default constructor can define only one but the named constructor can define more than one.

class Person{
  String name = "cdx";
  int age = 23;
  // Default constructor
  Person(this.name,this.age);
  Person.now(){
    print("Named constructor");
  }

  void getInfo(){
    print("The ${this.name}  The ${this.age}");
  }
}

main(List<String> args) {
  var p1 = new Person.now();// Name the constructor
}
Copy the code

5. Private properties/private methods

Dart does not have the public, private, and protected access modifiers that Java does.

Methods: Separate the class into a file, using “_” to make a method or property private.

Getter and setter modifiers

class Rect {
  num height;
  num width;
  Rect(this.height,this.width);
  get area{
    return this.height * this.width;
  }
  set areaHeight(value){
    this.height = value;
  }
}
main(List<String> args) {
  Rect r = new Rect(10.2);
  print("The area is:${r.area}");// Notice that the call accesses the area directly by accessing properties
  r.areaHeight = 6;
  print("The area is:${r.area}");
}
Copy the code

7. Static members

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 = 'cdx';
  static void showName() {
    print(name);
  }
}

main(List<String> args) {
  print(Person.name);
  Person.showName();
}
Copy the code
class Person {
  static String name = 'cdx';
  int age = 23;
  static void showName() {
    print(name);
  }
  void printInfo(){ // Non-static methods can access both static and non-static members
    print(name);// Access static properties
    print(this.age);// Access non-static properties
  }
}
main(List<String> args) {
  Person p = new  Person();
  p.printInfo();
}
Copy the code

8. Operators

? : conditional operator as: type conversion is: type judgment.. : Cascaded operations

class Person {
  String name = 'cdx';
  int age = 23;
  void printInfo(){
    print("The ${this.name}  The ${this.age}");
  }
}

main(List<String> args) {
  Person p1 = new  Person();
  p1.printInfo();//cdx 23
  Person p2;
  //p2.printInfo(); The method 'printInfo' was called on null.p2? .printInfo(); }Copy the code
p as Person  // Type conversion
Copy the code
class Person {
  String name = 'cdx';
  int age = 23;
  void printInfo(){
    print("The ${this.name}  The ${this.age}");
  }
}

main(List<String> args) {
  Person p1 = new  Person();
  p1.printInfo();//cdx 23p1.. name='xxx'
    ..age =20
    ..printInfo();//xxx 20
}
Copy the code

9, 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 of a character class

class Person {
  String name = 'cdx';
  int age = 23;
  Person(this.name,this.age);
  void printInfo(){
    print("The ${this.name}  The ${this.age}"); }}class Cdx extends Person{
  String sex;
  Cdx(String name, int age,String sex) : super(name, age){
    this.sex = sex;
  }

  void printCdx(){
    print("The ${this.name}  The ${this.age}  The ${this.sex} ");
  }

}
main(List<String> args) {
  Cdx c = new  Cdx('xxx'.20.'male');
  c.printInfo();//xxx 20
  c.printCdx();/ / XXX 20 men
}
Copy the code

10. Abstract classes

Abstract classes in Dart are used to define standards. Subclasses can inherit abstract classes or implement abstract class interfaces.

1. Abstract classes are defined by abstract keywords.

2. Dart abstract methods cannot be declared with abstract. Dart methods without a method body are called abstract methods.

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

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

5. An abstract class cannot be instantiated, but it can inherit its subclasses

The difference between extends and implements:

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

2. We implement abstract classes using Implement if we only use abstract classes as standards.

// To define an Animal class, its subclasses must include the eat method
// Solution: use abstract classes
abstract class Animal{
  eat();// Abstract methods
}
class Dog extends Animal{
  @override
  eat() {
    print("eat");
  }
}

main(List<String> args) {
  Dog dog = new Dog();
  dog.eat();
}
Copy the code

11, 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.

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();// Abstract methods
}
class Dog extends Animal{
  @override
  eat() {
    print("Dog eat"); }}class Cat extends Animal{
  @override
  eat() {
    print("Cat eat");
  }
}

main(List<String> args) {
  Animal dog = new Dog();
  dog.eat();//Dog eat

  Animal cat = new Cat();
  cat.eat();//Cat eat
}
Copy the code

12, interfaces,

Dart has interfaces just like Java. The difference between them is

Dart interfaces do not have the interface keyword to define the interface. Instead, ordinary or abstract classes can be found as interfaces

Dart is different, however. If you implement a common class, you will write all the methods needed for the common class and the attributes in the abstraction. And because abstract classes can define abstract methods, ordinary classes can’t, so in general you use abstract classes if you want to implement Java interfaces in the same way. It is also recommended to define interfaces using abstract classes.

abstract class Db{
  String url;
  add();
  save();
  delete();
}
class Mysql implements Db{
  @override
  String url;
  Mysql(this.url);
  @override
  add() {
    print("Mysql add");
  }
  @override
  delete() {
    print("Mysql delete");
  }
  @override
  save() {
    print("Mysql save");
  }
}
main(List<String> args) {
  Mysql mysql = new Mysql("xxxxxxx");
}
Copy the code

13, mixins

The Chinese word for “blend” is to mix other functionality into a class. For example, use it to implement something like multiple inheritance.

But as Dart releases continue to change, here are the conditions for using mixins in 2.x in Dart

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 neither inheritance nor interface, but a completely new feature.

//A,B cannot inherit from other classes, and A,B cannot have constructors
class A{
  void printA(){
    print("A"); }}class B{
  void printB(){
    print("B"); }}class C with A.B {

}
main(List<String> args) {
  var  c = new C();
  c.printA();
  c.printB();
}
Copy the code

8 and generic

Generics address the reuse of classes, interfaces, methods, and support for non-specific data types (type validation).

T getData<T>(T value){
  return value;
}
main(List<String> args) {
  print(getData(21));
  print(getData<String> ('xxxx'));
}
Copy the code
class PrClass<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(List<String> args) {
  PrClass p = new PrClass<String> (); p.add("111");
  //p.add(1); //type 'int' is not a subtype of type 'String' of 'value'
  p.printInfo();// Output: 111
}
Copy the code

Libraries in Dart

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'
Copy the code

2. System built-in library

import 'dart:math';
import 'dart:io';
import 'dart:convert';
/ / etc.

Copy the code

3, third-party package management system library (general PUB).

There are many examples.

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

2. Configure the name, description, and dependencies in the pubspec.yaml file.

3. Run pub get to download the package to the local PC.

4. Introduce the library into the project.

4. Finally, look at the documentation and use it.

Extend async and await

Async and await

Just remember to use these two key words:

1. Only async methods can call methods with the await keyword.

2. You must use the await keyword if calling other async methods.

Async is making methods asynchronous.

Await is waiting for an asynchronous method to complete.

main(List<String> args) async{
  var result = await testAsync();
  print(result);
}

// Asynchronous method
testAsync() async{
  return 'async';
}
Copy the code