[TOC]

Introduction to the

Dart is a programming language developed by Google and later recognized as a standard by Ecma (ECMA-408) [1]. It is used in the development of web, server, mobile application [2] and Internet of Things.

It is the programming language for Flutter.

An object-oriented, class-defined, single-inheritance language. It has a C-like syntax and can be translated into JavaScript, so it can support Web development. Both front and back end development are supported.

I met the dart

Dart for a preliminary look at the new Flutter project lib/main.dart:

The dart characteristics

  • Supports import/export, that is, import/export modules
  • object-oriented
  • class
  • Strongly typed
  • Support asynchronous

Dart Basic Syntax

Reference: Dart Grammar Reference site

variable

Create a variable and initialize the variable

// Variables store only object references
var name = 'bob'; 
// Dynamic variables, type detected only at run time
dynamic dynamicName = 'bob';
// Declare variables explicitly
String name = 'bob';
dynamicName = 1;
// dynamicName = dynamicName.toString() + '12e32w';
dynamicName =  '${dynamicName}12e32w';
Copy the code

If no value is assigned, the variable will be resolved to null

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

constant

Final and Const

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

The Const keyword is not just used to declare constant variables. It can also be used to create constant values,

final bar = const [];
var foo = const [];
// Non-final, non-const variables can be modified
foo = [1.2.3];
Copy the code

Built-in types

The Dart language supports the following built-in types:

  • Number
  • String
  • Boolean
  • Null
  • List (also known as ListArray)
  • Set A Set is a collection of unique and unnecessary elements.
  • Map
  • Rune (used to represent Unicode characters in strings)
  • Symbol

Number/String/Boolean/List

Both int and double are subtypes of num.

// A numeric integer
int lineCount=22; 
/ / floating point
double a=20; / / 20.0
/ / string
String name = 'bob'; 
/ / a Boolean type
bool flag = true;
// null
var d = null;
d??print('d is empty');// a?? . A If empty, the following code is executed

Copy the code

Note: the non-null judgment above?? Dart specific

List

No generics are specified

var list = [1, 2, 3];
Copy the code

Specifies the generic

var list33 = <String> ["a"."b"];
List<String> list7 = ['a'.'b'.'3'];
List<String> list8 = new List(2);
list8[0] = ('aaa');
print(list8);//[aaa, null]
Copy the code

Commonly used attributes

List<String> list13 = <String> ["aaa"."bbb"."ccc"];print(list13.length);The length / / 3
 print(list13.isEmpty);//false is null
 print(list13.isNotEmpty);//true indicates whether the value is not null
 print(list13.reversed);//(CCC, BBB, aaa) returns an inverted Iterable of the List without changing the original List
 print(list13.first);//aaa first element
 print(list13.last);// the last element of CCC
Copy the code

set

In Dart, a Set is a Set with unique and unnecessary elements.

// set
var halogens = {'fluorine'.'chlorine'.'bromine'.'iodine'.'astatine'};
// Create an empty set
var names = <String> {};// This creates a Map instead of a Set.
// var names = {}; 
 // This is ok.
Set<String> names = {};
Copy the code

Map

The map here is completely different from the MAP in JS

Map is the object used to associate keys and values. Keys and values can be any type of object.

No generics are specified

var gifts = {
  // Key: Value
  'first': 'partridge'.'second': 'turtledoves'.'fifth': 'golden rings'
};
// Use the Map constructor to create:
var gifts = Map(a); gifts['first'] = 'partridge';
gifts['second'] = 'turtledoves';
gifts['fifth'] = 'golden rings'; 
Copy the code

Specifies the generic

var map333 = <String.String> {}; map333["c"] ="c";
Map<int.String> map4 = new Map(a); map4[1] = "a";
map4[2] = "b";
Copy the code

Rune

In Dart, Rune is used to represent UTF-32 encoded characters in strings.

Symbol

A Symbol object represents the operator or identifier declared in the Dart program

Main use: API for referring to identifiers by name

// Get the Symbol of the identifier by adding a # to the literal Symbol.
#radix
#bar
Copy the code

function

Common function

Define a function

// Return type method name (parameter) {}
// The function returns no value
// The type is declared with void
// The return value defaults to null
void main(args) {
  ...
}
Copy the code

Function and the cords

// The function returns a value of type int
// The return value defaults to null
int sumValue(int a,int b) {
  int sum = a + b;
  print("The sum of a+b is:$sum"); 
  return sum;
}
Copy the code

Function passing parameters (optional)

void printCouties(String name1,String name2,[String name3]) {
  print("Civilized countries have:$name1");
  print("Civilized countries have:$name2");
  if(name3 == null) {print('Name3 does not exist');
  }else{
    print("Civilized countries have:$name3");
  }
}

printCouties('China'.'France'.'Germany');
printCouties('China'.'France');
Copy the code

Function parameter names assign default values

void findVolume(int width,int lenth, {int height = 20{})print("width:$width m");
  print("lenth:$lenth m");
  print("height:$height m");
}
Copy the code
The main () function

Any application must have a top-level main() function as an entry point to the application service. As called in the project!

Arrow function

The arrow function returns no value

sumValue(int a, int b)=>print(a + b);
Copy the code

Arrow functions have return values

int sumValue(int a, int b)=>a + b;
Copy the code
Anonymous functions
list.forEach((item) {
  print('${list.indexOf(item)}: $item');
});
Copy the code
Functions are first-class objects

A function can take arguments to another function. Such as:

void printElement(int element) {
  print(element);
}
var list = [1.2.3];
// Pass printElement as an argument.
list.forEach(printElement);
Copy the code

Dart Advanced Syntax

class

As the name implies, is an object that has the same properties (methods)

/ / define the class
class Student{
  int id; // int id=10; The default value
  String name; // String name="Mr wu";
  int age;
  void study(){
    print("The ${this.id}.The ${this.name}Learning the"); }}Copy the code

void main() {
    / / instantiate
  var student1 = Student();
  student1.id = 10;
  student1.name = "Mr wu";
  student1.study();
}
Copy the code

The constructor

The above calls are tedious and can be simplified by adding a constructor to the class

Constructor, which is executed automatically whenever the object is instantiated

class Student{...// Add the constructor
  Student(int id,String name){
    this.id = id;
    this.name =name;
  }
  // can be simplified as
  Student(this.id,this.name); 
 }
 / / instantiate
var student1 = Student(1.'luy');
var student2= Student(2.'monica');
Copy the code

Custom constructors

Student.myCustomConstructor(this.id, this.name,this.age);
// Create a custom constructor that needs to be instantiated using a class call
var student3=Student.myCustomConstructor(3.'momo'.30);
print("${student3.name} + ${student3.age}");
Copy the code

Class inheritance

Class inheritance is a common feature of many languages, and Dart also has it

Classes also have the same properties from class to class;

class Dog{
  String color;
  String name;
  void bark() {
    print("bark");
  }
  void eat() {
     print("eat"); }}Copy the code
class Cat{
  String color;
  int age;
  void meow() {
    print("meow");
  }
  void eat() {
    print("eat"); }}Copy the code

Like dog and cat, they both have colors, they eat, they have attributes and actions that animals have,

So there is a public class (animal), so that dog and cat inherit animal’s properties and methods directly;

class Animal {
  String color;
  void eat() {
    print("eat"); }}Copy the code

We often refer to these common classes as parent classes;

Extend Animal, retain its own characteristics

class Dog extends Animal{
  String name;
  void bark() {
    print("bark"); }}class Cat extends Animal{
  void meow() {
    print("meow"); }}Copy the code

Overrides parent methods and properties

class Dog extends Animal{
  void eat() {
    print("Dog eat"); }}Copy the code

When a class and its parent have the same method name, the code executes its own method in the class automatically

Class Getters and setters

Also known as computed properties, Getters and setters (also known as accessors and changers) allow a program to initialize and retrieve the value of a class field, respectively.

Mainly used when there is linkage between properties. If you change the length, width, area, length or width of a rectangle, the area will change.

Get area {return this.height * this.width; }

class Rect {
  num height;
  num width;
  Rect(this.height, this.width);
  / / get methods
  get area {
    return this.height * this.width;
  }

  / / set methods
  set areaHeight(value) {
    this.height = value;
  }
  / / set methods
  set areaWidth(value) {
    this.width = value; }}Copy the code
void main() {
  Rect r = new Rect(10.4);
  print(r.area);
  // Call set
  r.areaHeight = 6;
  r.areaWidth = 5;
  // Access the area directly by accessing properties
  print("The area:${r.area}");
}
Copy the code

Abnormal capture

As with most syntax, try {} catch{}

 void depositMoney(int amount){
    if(amount<0) {throwError; }}try {
   depositMoney(- 1);
  } catch(e){
    print("err is $e");
  }
Copy the code

Dart has a class, Exception, that encapsulates Exception handling

 try {
   depositMoney(- 1);
  } catch(e){
    print(e.errorMessage());
  }
// The method to implement the exception
class DepositException implements Exception{
  String errorMessage(){
    return "Not less than $0"; }}Copy the code

API

Conversion between types

Note: Strong typing does not support implicit conversions

any->string

dynamic age = 2;
age = '$age';
Copy the code

int -> string

age.toString();
Copy the code

string -> int

int.parse('100');
Copy the code

String -> double

var onePointOne = double.parse('1.1');
Copy the code

double->String

String piStr = 3.141592.toStringAsFixed(3); // Result is 3.141
Copy the code

other

    double figureB = 64.742;
    // return the integer value of figureB
    print(figureB.toInt());
    // return the double value of figureB
    print(figureB.toDouble());
    // returns a double value greater than figureB
    print(figureB.ceilToDouble());
    // returns a double value less than figureB
    print(figureB.floorToDouble());
    // returns the rounded double value of figureB
    print(figureB.roundToDouble());
    // return figureB as a string with a few decimal places
    print(figureB.toStringAsFixed(2));
    // returns the exact result of figureB with a few decimal places reserved
    print(figureB.toStringAsPrecision(3));
Copy the code

Data type API

int
    int figureC = 31;
    // figureC compares other integers: 0: same, 1: greater, and -1: smaller
    print(figureC.compareTo(20));
    // Set figureC to an integer in the specified range
    print(figureC.clamp(20.25));
    // Return figureC converted to the specified base (base) string
    print(figureC.toRadixString(16));

    int figureD = 12;
    // Return the greatest common divisor of figureD with other integers
    print(figureD.gcd(18));
    // Return the cut remainder of figureDg and other integers
    print(figureD.remainder(18));
    // Returns a string of powers of figureD
    print(figureD.toStringAsExponential(2));
Copy the code
string

Dart is unique: three single quotes or three double quotes,

// Use three single quotes or three double quotes to create a multi-line string with built-in formatting, such as newlines and indentation, and whatever output is written inside.
    String e = '''asd fdsd fff ''';
Copy the code

Common string attributes

    String a20 = "aaaa";
    String a21 = "";
    print(a20.length);//4 The value is a character string
    print(a20.isEmpty);//false is null
    print(a20.isNotEmpty);//true indicates whether the value is not null
    print(a21.isEmpty);//true
    print(a21.isNotEmpty);//false
Copy the code

String conjunction

    String a = "abcdefg";
    String b = '12345';
    String c = a + b; // Use the + sign to connect
    String d = 'aaa' 'bbb'; // Two strings must not be variables
    print(c); //abcdefg12345
    print(d); //aaabbb
Copy the code

String template

Use ${} to embed a string variable into another string

    String a1 = "aa";
    String b1 = "bb${a1}bb";
    print(b1); //bbaabb
    String b2 = "bb${a1.toUpperCase()}bb";
    print(b2); //bbAAbb
Copy the code

String cutting

    String a2 = "aaabbb";
    print(a2.substring(0.2)); //aa includes the head but not the tail
    print(a2.substring(3)); // BBB from index to end
    String a5 = "a,d,d d,c,,";
    List<String> a6 = a5.split(",");// Split returns an array
    print(a6.length); / / 6
    print(a6); //[a, d, d d, c, , ]

    String a8 = "a b,c";
    String a7 = a8.splitMapJoin(",".// Query ", ", replace "with the return value of onMatch," replace other with the return value of onNonMatch
        onMatch: (Match match) {
          return "a";
        }, onNonMatch: (String nonMatch) {
          return "b";
        });
    print(a7);//bab a b,c => bab
Copy the code

The ** string determines the **

Whether to contain or end with XXX

    String a3 = "aaabbbccc";
    print(a3.startsWith("aa")); //true
    print(a3.startsWith("aa".3)); //false Start with index=3
    print(a3.endsWith("c")); //true
    print(a3.contains("ab")); //true
    print(a3.contains("ac")); //false
    print(a3.contains("ab".3)); //false Start with index=3
Copy the code

String substitution

    String a4 = "abcdeab";
    print(a4.replaceAll("ab"."cc"));// replace all qualified cccdecc
    print(a4.replaceFirst("ab"."dd"));//ddcdeab replaces only the first one that meets the condition
    print(a4.replaceFirst("ab"."dd".3));//abcdedd replaces the first one with index=3eligibleprint(a4.replaceRange(1.3."z"));// Replace the range from 0 to 3 with 0 but not 3
    print(a4.replaceAllMapped("c", (Match match){//abyydeab returns the value from the methodReplaces the specified stringreturn "yy";
    }));
    print(a4.replaceFirstMapped("b", (Match match){// abcDEA333 replaces the specified string with the method return value starting with index=2
      return "333";
    },2));
Copy the code

String lookup

    String a9 = "aababcc1bc23";
    print(a9.indexOf("ab"));//1 The first index that matches the condition
    print(a9.indexOf("ab".2));// start index=2
    print(a9.indexOf("ab".4));// index=4; // index=4
    print(a9.lastIndexOf("bc"));//8 Returns the first index that matches the condition from back to front
    print(a9.lastIndexOf("bc".3));// select * from index=3 and return -1
    print(a9.lastIndexOf("bc".7));// start index=7 and return the first index that meets the condition
Copy the code

Convert to case

    String a10 = "aaBBCc";
    print(a10.toLowerCase());//aabbcc
    print(a10.toUpperCase());//AABBCC
Copy the code

Remove the blank space

    String a11 = " aab bcc ";
    print(a11);// aab bcc
    print(a11.trim());//aab BCC remove the left and right Spaces
    print(a11.trimRight());// aab BCC removes the right space
    print(a11.trimLeft());// aab BCC // remove left Spaces
Copy the code

The remaining bits of the complement length are replaced with the specified string

    String a13 = "111";
    print(a13.padLeft(6));// the remaining three bits are completed by default
    print(a13.padRight(6."c"));  // 111CCC specifies the remaining 3 bits to use "C"
    print(a13.padRight(6."dd"));  // 111DDDDDD three bits each bit specifies that the total length is not 6 after "dd" is used
    print(a13.padLeft(2."e"));//111 Returns the original string if the specified length is less than the original string length
Copy the code

Sequential string comparison

    String a12 = "bbcc";
    print(a12.compareTo("aaa"));//1 B > A in the ASCII code
    print(a12.compareTo("bbcc"));/ / 0
    print(a12.compareTo("dd"));//-1 b
Copy the code
List
List ListFollow = [1.2.3];
ListFollow.add(9);
list5[1] = 4;
Copy the code

The following methods are available for specific reference

AddAll () merges two lists

Insert (index,element) Inserts a value at the specified index

InsertAll (index,list) Inserts a list at the specified index

FollowedBy (list) combines itself with a list of arguments

Remove (item) Removes a specific element removeAt(index) Removes the index position element

EmoveLast () deletes the last element removeRange(start,end) range removeWhere() deletes according to the condition

Clear () clears the array

Modifies the value of the specified index position

SetRange (startIndex,endIndex,list) range Changes the list value

ReplaceRange (start,end,list) range to replace a header without a tail

FillRange (start,end,value) Replace each element from start-end with value

RetainWhere (()=>(bool)) Filters elements based on conditions

SetAll (index,list) Starts at index and replaces each element in the list one by one

View the value of the index position

IndexOf (element,[start]) finds the indexOf the specified element in the list

Any ((element)=>(bool)) Checks whether any element in the List matches the given parameter

Every ((element)=>(bool)) determines whether every element in the List conforms to the argument function

Contains (obj) List whether the given OBj exists

FirstWhere ((element)=>(bool)) returns the first element that meets the condition (not the element’s index)

traverse

ListFollow.forEach((item) {
 print(item);
});
Copy the code
Map

Note: the map here is completely different from the JS map

A key-value was added or modified

Map<String.int> map7 = {"a":1."b":2."c":3."d":4."e":5};
// Add a key value
map7["f"] = 6;
// Change a key value
map7["a"] = 11;
// update() changes the value of the specified key
int result3 = map7.update("c", (value)=>(value*2));
print(result3); / / 6
Copy the code

UpdateAll () batch modifies the map based on the rules of the parameter function

 Map<String.int> map24 = {"a":1."b":2."c":3};
 map24.updateAll((String key,int value){
    return value*2;
 });
 print(map24);//{a: 2, b: 4, c: 6}
Copy the code

Remove () removes a key

map24.remove("c");
Copy the code

RemoveWhere () Deletes batches based on conditions

map7.removeWhere((key,value)=>(value>3));
Copy the code

ContainsKey () Specifies whether it contains a key

print(map7.containsKey("d"));
Copy the code

ContainsValue () specifies whether it containsValue, as above

Traverse the forEach ()

 Map<String.int> map12 = {"a":1."b":2."c":3."d":4."e":5}; 
map12.forEach((String key,int value){
  print("$key  $value");
}
Copy the code

Clear () empty map

AddAll () combines the entire map generic to be consistent

map12.addAll(map7) 
Copy the code

Dart is unique: Merge maps and de-weigh them

AddEntries () merges two maps. If keys are duplicated, the value of the merged map overwrites the value of the merged map

 Map<String.int> map26 = {"a":1."b":2."c":3};
 Map<String.int> map27 = {"a":1."b":4."d":3."e":5};
 map26.addEntries(map27.entries);
Copy the code

Add data to attributes

PutIfAbsent () gets the value if the key is present, adds it to the map if not, and returns the attribute value

Map<String,int> map18 = {"a":1,"b":2,"c":3}; int result = map18.putIfAbsent("a", ()=>(2)); Int result2 = map18. PutIfAbsent ("d", ()=>(2)); // There is no return value 2Copy the code