A study plan

  • Dart concepts, using background understanding
  • Dart basic syntax learning, variables, built-in types, functions
  • Dart important syntax classes, interfaces, mixins features, and more
  • Dart’s important syntax is generics, type definitions
  • Implementation of important Dart syntax libraries, common Dart libraries, and use of asynchronous support
  • Dart versus JavaScript and TypeScript type systems

The Dart concept

  • Dart is a new object-oriented programming language that you can use as JAVA or JavaScript; It’s simpler and easier to understand than JAVA, more formal and engineered than JavaScript
  • Dart is the official development language for Google’s future operating system, Fuchsia, and has been developed into a mobile development framework called Sky, which was later named Flutter.
  • Dart is an application-layer programming language with its own DartVM engine
  • Dart2.0 + is a more secure strongly typed language
  • Dart development in three directions: mobile development, DartVM command line (Server side), and browser (front end)

The characteristics of the Dart

  • Single-process asynchronous event model;
  • Strongly typed, type inferred;
  • DartVM, with extremely high performance and excellent code execution optimization, is comparable to Java7 JVMS based on earlier benchmarks;
  • Unique Isolate, which enables multi-threading;
  • Object-oriented programming, all data types are derived from Object;
  • Operator overloading, generic support;
  • Powerful Future and Stream models make it easy to implement efficient code;
  • Minix feature, can better realize method reuse;
  • Null security operations such as NullableObject? Dosth ();
  • Full platform language, can be well suited for mobile and front-end development.
  • Syntactically, Dart provides a lot of convenience that can significantly reduce code. For example,a character link can be “My name isname, ageisName,ageisname, ageisage” without + sign concatenation or type conversion.
  • . Needless to

Dart Language Basics

The Dart variable
Dart is a powerful scripting language that does not pre-define variable types, and automatically type inferences that variables defined in DART can passvarKeywords, variables can be declared by type such as:var str='this is var';

String str='this is var';

int str=123;
 
Object name = 'Bob';
dynamic name = 'Bob'; // If the object is not limited to a single type, you can specify object type or dynamic typeNote:varDo not write type after, do not write typevarBoth writtenvar  a int  = 5; The default value of an uninitialized variable isnull

int lineCount;
assert(lineCount == null);
Copy the code
Dart constants: final and const modifiers
// Const is always the same

// Final can start without assigning only once; 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
 
// Never change the quantity of the quantity, use final or const instead of using var or other variable types.
 
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
Dart data type
String, Number(int, double), Boolean, List, Map, Set, Rune, Symbol(the last two are almost not used)

// Use triple quotation marks "" with single or double quotation marks to represent multi-line strings

// Create a "raw" string with the r prefix (often used with regular expression strings):
var s = r'In a raw string, not even \n gets special treatment.';

$variableName (or ${expression}) string concatenation
var str = "my name is $name, age is $age";

int a=123;
double b=23.5;
num c=123; // this is equivalent to the union of int and double

/* Reversed isEmpty reversed isNotEmpty reversed isNotEmpty reversed isNotEmpty reversed isNotEmpty reversed isNotEmpty Remove Remove fillRange remove fillRange insert(index,value); insert(index,value); InsertAll (index,list) insertAll(index,list) insert list toList() other types convert toList join() list converts to string split() string converts toList Maps are unordered key-value pairs: Keys obtain all the keys values values obtain all the values isEmpty whether isNotEmpty isEmpty whether isNotEmpty isNotEmpty common methods: remove(key) remove the data of the specified key addAll({... List, Set, and Map are called collection types. They have the following common property methods: isEmpty; isNotEmpty; foreach Map where => is equivalent to JS filter method any => is equivalent to JS some method every */

Copy the code
Dart operator, operator, conditional expression, loop statement
Dart operators, operators, conditional expressions, loop statements, and so on are similar to JSisOperator for type determination, usingasOperator to cast an object to a specific typeprint(p is Object);

// If b is empty, the variable is assigned to b; otherwise, the value of b remains unchanged. (?????? ,? Dart object operator is also available, similar to JS.)b ?? = value;ToString () toString()
Parse () int. Parse ()

/ / = =, if (...). The type in such expressions will not be converted implicitly, which is completely different from JS, and requires explicit value checking
// Check for empty strings.
var fullName = ' ';
assert(fullName.isEmpty);

// Check the value of 0.
var hitPoints = 0;
assert(hitPoints <= 0);

// Check for null values.
var unicorn;
assert(unicorn == null);

/ / check NaN
var iMeantToDoThis = 0 / 0;
assert(iMeantToDoThis.isNaN);
Copy the code
function
// void: No declaration return value is displayed
void func(){}

// If a function has no explicit return, it returns NULL by default.
fun(){}
assert(fun() == null)

// Optional parameters can be named or positional parameters, but a parameter can be modified in either way
void enableFlags({bool bold, boolhidden}) {... } enableFlags(bold:true, hidden: false);

void enableFlags(bool bold, [boolhidden]) {... } enableFlags(true.false);


// In the following code.. The syntax is cascade. With cascading invocation, you can simplify multiple operations on an object (like chain calls in jquery)
void main() {
  querySelector('#sample_text_id')
    ..text = 'Click me! '
    ..onClick.listen(reverseText);
}

// If the function has only one expression (only one statement), you can use the shorthand syntax:
bool isNoble(intatomicNumber) => _nobleGases[atomicNumber] ! =null;
Copy the code

Dart language advanced

class
Everything in Dart is an object, and all objects inherit fromObjectClass. Dart is an object-oriented language that uses classes and single inheritance. All objects are instances of classes, and all classes areObjectA class usually consists of attributes and methods, similar to the es6 class conceptclass Person{
Dart differs from other object-oriented languages in that there are no public private protected access modifiers in Data, but we can use _ to make an attribute or method private. * /
  String _sex;   // Private attributes
  
  // Use the static keyword to implement class-level variables and functions
  Static methods cannot access non-static members. Non-static methods can access static members
  static int height = 170;
  static void show() {
     print(height);
  }
  
  String name;
  int age; 
  // Default constructor and initialize instance variables
  // Person(String name,int age):name=' c ',age=10{
  // this.name=name;
  // this.age=age;
  // }
  // Short for the default constructor
  Person(this.name,this.age);
  
  Person.now(){
    print('I'm a named constructor');
  }
  void printInfo(){   
    print("The ${this.name}----The ${this.age}");
  }
  void _run(){
    print('This is a private method');
  }
  execRun(){
    this._run();  // The public method can be used to call the private method}}// Person p1= Person(' Person ', 20); The default constructor is called when the class is instantiated by default
// Person p1= Person.now(); // Call the named constructor

A subclass extends from its parent class using the extends keyword. 2. A subclass inherits properties and methods visible in its parent class but does not inherit constructors
class Person {
  String name;
  num age; 
  Person(this.name,this.age);
  Person.xxx(this.name,this.age);
  void printInfo() {
    print("The ${this.name}---The ${this.age}"); }}class Web extends Person{
  String sex;
  // instantiate the child class to pass arguments to the parent constructor
  Web(String name, num age) : super(name, age);
  
  // Instantiate the child class to pass arguments to the parent class named constructor
  Web(String name, num age,String sex) :    super.xxx(name, age){
    this.sex=sex;
  }
  
  run(){
    print('run');
    super.work();  // Subclasses call methods of their parent class
  }
  
  // Override the parent method
  @override       // It is recommended to override the parent method with @override
  void printInfo(){
     print("Name:The ${this.name}- age:The ${this.age}"); }}Copy the code
Abstract classes, interfaces, mixins, enumerated types

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

  1. The abstract class passesabstractKeyword to define
  2. Abstract methods in Dart cannot be declared with abstract. Methods without a method body in Dart are called abstract methods.
  3. If a subclass inherits an abstract class, it must implement its abstract methods
  4. If you use an abstract class as an interface implementation, you must implement all properties and methods defined in the abstract class.
  5. Abstract classes cannot be instantiated, only subclasses that inherit from them can. (If you want an abstract class to be instantiated, you can do so by defining a factory constructor.)

The difference between extends and implements:

  1. If we want to reuse methods from an abstract class, and we want to constrain our own class with an abstract method, we use itextendsInheriting abstract classes
  2. If we were just using abstract classes as a standard, we wouldimplementsImplementing abstract classes
abstract class Animal{
  eat();   // Abstract methods
  run();  // Abstract methods
  printInfo(){
    print('I'm a normal method in an abstract class.'); }}class Dog extends Animal{
  @override
  eat() {
     print('The dog is eating a bone');
  }

  @override
  run() {
    // TODO: implement run
    print('The dog is running'); }}class Cat extends Animal{
  @override
  eat() {
    // TODO: implement eat
    print('The kitten is eating the mouse');
  }

  @override
  run() {
    // TODO: implement run
    print('The kitten is running'); }}Copy the code

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, however, is a bit odd. If you implement a generic class, you’ll need to overwrite all the methods of the generic class and the attributes in the 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

abstract class Db{   // Interface: conventions, specifications
    String uri;      // Database link address
    add(String data);
    save();
    delete();
}

class Mysql implements Db{
  
  @override
  String uri;

  Mysql(this.uri);

  @override
  add(data) {
    // TODO: implement add
    print('This is mysql add method'+data);
  }

  @override
  delete() {
    // TODO: implement delete
    return null;
  }

  @override
  save() {
    // TODO: implement save
    return null;
  }

  remove(){
      
  } 
}

class Mongodb implements Db{
  @override
  String uri;
  @override
  add(String data) {
    print('Here's the add method for Mongodb'+data);
  }

  @override
  delete() {
    // TODO: implement delete
    return null;
  }

  @override
  save() {
    // TODO: implement save
    return null;
  }
}

Mysql mysql=new Mysql('xxxxxx');
mysql.add('1243214');
Copy the code

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

Mixins can be used in Dart 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:

  1. Classes that are mixins can only inherit from Object, not from other classes
  2. Classes that are mixins cannot have constructors
  3. A class can mixins multiple mixins classes
  4. Mixins are far from being an inheritance or an interface, but rather an entirely new feature
  5. If mixins do not want to be used as regular classes, use keywordsmixinreplaceclass
class A {
  String info="this is A";
  void printA(){
    print("A"); }}class B {
  void printB(){
    print("B"); }}class C with A.B{}/* What is the instance type of mixins? Quite simply, the type of a mixins is a subtype of its superclass. * /
var c=new C();  
print(c is C);    //true
print(c is A);    //true
print(c is B);   //true
Copy the code

Enumeration types, also called Enumerations or enums, are special classes that represent a fixed number of constant values.

Use enumerated

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

Each value in an enumeration has an Index getter method that returns the position of the value in the enumeration type definition (starting at 0). For example, the index of the first enumeration value is 0 and the index of the second enumeration value is 1.

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

Using the enumeration’s values constant, get a list of all enumerated values.

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

Enumeration types have the following limitations: Enumerations cannot be subclassed, mixed, or implemented. Enumerations cannot be explicitly instantiated.

Generics, type definitions

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

String getData1(String value){
    return value;
}

int getData2(int value){
   return value;
}
  
// Both string and int are supported
getData<T>(T value){
      return value;
}
print(getData<int> (12));

When implementing generic types, you may want to restrict the types of their parameters. You can use extends.
class Foo<T extends SomeBaseClass> {
  // Implementation goes here...
  String toString() => "Instance of 'Foo<$T> '";
}

class Extender extends SomeBaseClass {... }// You can use SomeBaseClass or any of its subclasses as a generic argument:
var someBaseClassFoo = Foo<SomeBaseClass>();
var extenderFoo = Foo<Extender>();

// It is also possible to specify no generic arguments:
var foo = Foo();
print(foo); // Instance of 'Foo<SomeBaseClass>'

// Specifying any type other than someBaseclass will result in an error:
var foo = Foo<Object> ();Copy the code

Type definitions, type aliases typedef, type like TS but only for methods

typedef int Add(int x, int y);

main() {
  Add add = (x, y) => x + y;

  var sub1 = add(1.'2');  // Error: Cannot assign a String parameter to an int parameter

  var sub2 =  add(1.2);  / / - > 3
  print(sub2 is int);     // -> true

}
Copy the code

A method type alias named Add is defined above, which is the type of method Add. An error is reported because the parameter type passed to sub1 does not match that defined by Add. Because Add defines that the Add method returns an int, (sub2 is int) is true

library

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 libraries

  import 'lib/xxx.dart';
Copy the code

2. System built-in library

  import 'dart:math';    
  import 'dart:io'; 
  import 'dart:convert';
Copy the code

3.Pub Library in the package management system

pub.dev/packages pub.flutter-io.cn/packages pub.dartlang.org/flutter/

Yaml file and configure the name, description, and dependencies. 3.3 Run pub get to get the package and download it to the local directory. 3.4 Import library import ‘package:http/http.dart’ as http; See the document and use it

// Name conflict rename
import 'package:lib1/lib1.dart';
import 'package:lib2/lib2.dart' as lib2;

Element element1 = new Element(a);// Uses Element from lib1.
lib2.Element element2 = new lib2.Element(a);// Uses Element from lib2.

// Partial import
import 'package:lib1/lib1.dart' show foo; // Import only the required parts, using the show keyword
import 'package:lib2/lib2.dart' hide foo; // To hide unwanted parts, use the hide keyword

// Lazy loading, using the deferred as keyword
import 'package:deferred/hello.dart' deferred as hello;

// When needed, use the loadLibrary() method to load:
 greet() async {
      await hello.loadLibrary();
      hello.printGreeting();
 }
Copy the code

Library split, part and part of see juejin.cn/post/684490…

Asynchronous support

Future => exactly the same as ES6 Promise

Stream => Is used for file uploading and continuous request loading

Similarities and differences with JavaScript and TypeScript

See Dart vs JavaScript vs TypeScript

Dart pit log

To be updated…