Dart there is a reason why we have to learn, because there is the God Flutter, but I can’t do it at this stage as unconstrained as some gods

If you are familiar with object orientation and basic programming concepts such as variable, loop, and conditional control, you can complete this tutorial. You don’t need to know Dart or have experience with mobile development

Worship the great god…… Dart feels familiar at first, because higher-level languages are converging, and Dart is a combination of strongly typed and weakly typed languages, so you can’t skip it because much of the code is not clear. Again, for myself, if I don’t walk through the Dart system, I still feel hazy, which is very uncomfortable

This article is intended to help those who are new to Dart. It covers the basic syntax, but Dart’s multi-threaded, asynchronous nature is not part of this article. That’s for the next article. At the same time their own operation, write again notes, so remember clearly, but also for the sake of the future, people have left a name, a passing voice, we learned not to write blog how to prove that we have learned, after forget how to do, that is to learn in vain, I hope you all write their own notes blog, write articles

I wrote very along with their own meaning, everyone don’t like the words please look at the following to write very standard:

  • Complete the Dart (1)
  • Complete the Dart (2)
  • Foundation of Flutter (III) A quick introduction to Dart

Dart history and brief introduction

Before learning a language, we learn about the history of the language and there are always some good things to learn. Let’s look at the introduction of the language again, which always makes it easier for us to learn later

This paragraph is from Basics of Flutter (III) A Quick Introduction to Dart

The Dart history

Dart is a computer programming language developed by Google that debuted in October 2011. The latest version is Dart2. Dart was created by Google engineers who were unhappy with JavaScript, and early on it won over some front-end developers. However, as JavaScript caught on with NodeJS and became ubiquitous on the front end, back end, and mobile, Dart fell into oblivion. Dart was pretty powerful, but unlucky

Google isn’t giving up on Dart. It’s promoting Dart: Google’s Angular version of Dart, designating Dart as the official development language for the new system Fuchsia, and Dart as the development language for the mobile UI framework Flutter, has brought Dart back into the picture. Dart normally runs on DartVM, but under certain circumstances it can also compile local code to run on hardware, such as the Flutter, which compiles code to platform native code to improve performance

Dart features:

  • Fast execution speedDart is AOT(Ahead Of Time) compiled into fast, predictable native code, which allows Flutter to be almost always written using Dart. JIT (Just In Time) compilation is also possible.
  • Easy to transplantDart can be compiled into ARM and X86 code, so Dart can run on Android, iOS, and elsewhere. Easy to get started, Dart leverages advanced language features, and if you’re already familiar with C++, C, and Java, Dart can be developed in a matter of days
  • Easy to readDart eliminates the need for a separate declarative layout language (XML or JSX), or a separate visual interface builder, because Dart’s declarative programming layout is easy to read.
  • Avoid preemptive schedulingDart can do object allocation and garbage collection without locks. Like JavaScript, Dart avoids preemptive scheduling and shared memory, so locks are not required.

The Dart description:

  • In Dart, everything is an Object, each Object is an instance of a class, and all objects inherit from Object.
  • Dart parses all the code before it runs, specifying data types and compile-time constants to make the code run faster.
  • Unlike Java, Dart does not have the keywords public, protected, and private. If an identifier starts with an underscore _, both it and its library are private.
  • Dart supports top-level functions such as main(), as well as static and instance methods for classes or objects, and can create functions inside functions.
  • Dart supports top-level variables, as well as static variables of a class or object and instance variables, sometimes called fields or properties.
  • Dart supports generic types such as List (a List of integers) or List (a List of objects of any type).
  • The Dart tool can report two types of problems: warnings and errors. A warning simply states that the code may not work properly, but it does not prevent the program from executing. Errors can be compile-time or runtime. Compile-time errors prevent code execution; Runtime errors cause code execution to report an exception.

Dart Keyword list:


The Dart features

A lot of articles on the Web say that Dart incorporates high-level language features on top of Java, but can I just say that the latest version of Java doesn’t? So to say so is to say nothing

If I say Dart = Java + Kotlin, Dart = Java + Python is the best if you’ve ever been in Python, Dart allows you to write either traditional Java style code or Python style code, I’ll try to show you in what ways Dart is like Python

1. Places like Python

  • 1.1 Dart support library developmentpythonAll the classmates know what’s going on injavaLet’s create aclassThe file must create a class with the same name as the file
public class Name {... }Copy the code

But Dart allows you to write properties, methods, and libraries to others without creating classes in the Dart file

DartLib code:

var name = "NAME";

void function1() {
  print(name);
}

void function2() {
  print("BBB");
}
Copy the code

Import to use as a library

import 'package:flutter_app4/DartLib.dart' as Lib;

void test(){
  Lib.name = "FUN";
  Lib.function1();
}
Copy the code
  • 1.2 Dart allows you to declare variables just like Python
var book = Book("AA".18);
Copy the code
  • 1.3 Dart, like Python, can declare methods with writable or unwritable return values, and the compiler will automatically determine the return type
  sum( var num1){
    return num1 + 10;
  }
Copy the code
  • The difference between Dart and Python is that Dart cannot omit parameter types everywhere, as Python does. Dart must write parameter types.{},;You have to, or Dart will really be python

2. Dart supports the var dynamic type

Dart supports both static and dynamic typing, and with the high level language features, you can write as you like, in the traditional Java object-oriented, object-everywhere style of code, like Kotlin, like Python, but the differences are getting smaller and smaller. The difference between Dart and Python is pretty small. To be honest, I prefer Python. Minimalism is magical

3. Dart has performance advantages

Dart can do object allocation and garbage collection without locks. Just like JavaScript, Dart avoids preemptive scheduling and shared memory (and therefore locks), so Dart can more easily create smooth animations and transitions that run at 60fps. This is something you’ll be impressed with once you’ve developed an App with Dart


Basic data type

Dart Basic data types:

  • Dynamic type –var,dynamic
  • Numeric –Num,int,double,bool(Boolean)
  • The collection type –List,MapDart has no concept of arrays. Arrays are collections
  • The text type –String
  • Methods class –Function

Here’s a closer look:

1. varanddynamicYes dynamic typing

2. New types of mathNum

Int, double, double, double, double, double, int, double, double, double, double, double

  num name = 10;

  void test() {
    name = 11;
    name = 11.2;
  }
Copy the code

Dart does not require non-null values like Kotlin

var name ;
Copy the code

4. Features of var

If the var variable is null, you can give it whatever value you want, but as long as the var variable has a specific type, it’s only going to be of that type, right

  / / OK
  var name ;
  void test() {
    name = 11;
    name = "AA";
  }
  
  // This error is reported
  var name = 10;
  void test() {
    name = 11;
    name = "AA";
  }
Copy the code

5. dynamic

So dynamic is an indeterminate type and it’s the same as var, but var is for developers, and dynamic is used within Dart, so we can also write dynamic, but it’s usually hidden, so there’s no automatic prompt for dynamic, So Dart doesn’t recommend that we use dynamic, but we know what dynamic means: A variable decorated by dynamic can be assigned to any type of value, right


The operator

Don’t say the usual ones, say some changes

1. /

In Java, round 5/3=1; But in Dart, instead of rounding, you have the decimal point, 5/3=1.6666…

2. ~ /

That’s rounding in Dart, 5/3=1

3. = =

Dart == does not determine whether the reference is the same, but rather whether the two sides of the equal sign are the same

4. identical(name1, name2)

Identical is the difference in the Dart

5. ?? =

If the parameter ==null, then the number after =, of course, you use?? It’s ok, too,?? You can put expressions on both sides

var name;
print(name ?? =10);
~~~~~~~~log~~~~~~~~~~~
I/flutter: 10
Copy the code

6. = >

One line can omit {}

Function test1 = (var name, var age) => print(name + age);
Copy the code

7. .

It’s easy to chain calls

    var book = Book("AA".12)
      ..name = "BB"
      ..age = 15;
Copy the code

8. ? .

If null, no error is reported

  var book = Book("AA".12."CC"); book? .name ="BB";
Copy the code

9. is,is!,as

Type determination, conversion type, I won’t go into detail, everybody knows

  if (book1 is Book) {
    book1.name = "AA";
  }

  (book2 as Book).name = "DD";
Copy the code

switch

Switch Cases in Dart support basic data types and object types. In addition, you can alias each case to specify a jump to a case execution code

    var name = "BB";
    switch (name) {
      as:
      case "AA":
        print("AA");
        break;
      case "BB":
        print("BB");
        continue as;
        break;
      case "CC":
        print("CC");
        break;
    }
    
~~~~~~~~~log~~~~~~~~~
I/flutter: BB
I/flutter: AA
Copy the code

For example, if we add “as” to case AA, we can use the “continue” keyword in BB to jump to case AA and execute the code regardless of whether the “AA” character is qualified or not


A change in method

1. Methods in Dart always have a return value, even if we writevoidIt’s actually going backnullJust so you know

2. Parameter pattern

Dart uses {} for optional arguments and [] for positional arguments

  // This parameter is optional. Use xx:xx to pass the value
  void test1(var name1, {var name2 = 10.var name3 = 20{})print("result = $name1,$name2,$name3");
  }
  
  If you want to assign a value to name3, you must first assign a value to name2
  void test2(var name1, [var name2, var name3]) {
    print("result = $name1,$name2,$name3");
  }
  
  test1("AA", name2: 55);
  test2("BB".18.19);
Copy the code

3. Methods are all objects

Dart is a high level language. Everything is explained, and the method itself is no different. Anyone familiar with Koltin or Python is not going to make a living

  void man(){
    print("man");
  }
  
  var f = man;
  f();
Copy the code

For example, we can declare a property object, assign another method to the object, and then run the method by adding ()

4. Parameter methods

Let’s look at the use of methods as parameters in Dart

  // Declare the method
  void textView(void click(var name)) => click("AA");
  // Usage
  textView((var name) => print(name));
Copy the code

5. Anonymous methods

Dart returns a value (parameter type, parameter name, XXX){}. If you don’t have a return value, you can use => instead of {}.

Here’s an example:

void textView(String click(var name)) => click("AA");
  
textView((var name) {
  print(name);
  return "AA";
});
Copy the code

6. Closure

Dart closures, like JS and Python, are methods defined inside methods that have the following properties:

  • A closure is an object
  • Closures are defined inside other methods
  • A closure can access the layout variable of an external method and hold its state. This is where closures are most useful. They expose properties inside a method, and because methods return methods, Dart’s methods are objects that can be treated as return values

A lot of people say that closures can not learn, read a lot of information or don’t understand, in fact, let’s say this to everyone: everyone regards closures as objects

For example, in the following example, we take the closure, and the data of the outer method is constantly increasing. We call the closure several times, and you will see that the z-valid data keeps increasing

/ / closures
sum(){
  var num = 0;
  sum2(){
    num+ +;print(num);
  }
  return sum2;
  
  // Anonymous is the most common way to write
  return() {num+ +;print(num);
  };
}

// Call the closure several times
void main(){
  Function a = sum();
  a();
  a();
  a();
  a();
  a();
  a();
}

~~~~~~~~~~log~~~~~~~~~~
1
2
3
4
5
6
Copy the code

The results are not deceptive. Consider a closure as an anonymous implementation class that contains outer data, and it is easy to see it as an object. This is the classic example


Changes in object orientation

1. It can be omittednew

As mentioned earlier, Dart creates objects that omit new, which is a great design and experiences python minimalism

var book = Book("AA".12);
Copy the code

2. Dart is provided by defaultget/setmethods

3. Methods in Dart cannot be overloaded

4. The DartPublic and private

Dart is visible in terms of libraries. Each Dart file is a library. In Dart, _ means that the library is private

// Such an object is not to be used anywhere except in the library file
class _Book {
  var name, age;

  _Book(this.name, this.age);

  speak(){

  }
}
Copy the code

5. Calculate attributes

The Dart property automatically generates get and set methods by default, but you can also write your own.

class RectTest {
  var width, height;

  RectTest(this.width, this.height);

  get area => width * height;

  set area(value) => width = value;
}

void main() {
  var rect = RectTest(20.12);
  print(rect.area);
  rect.area = 30;
  print(rect.area);
  print(rect.width);
}

~~~~~~~~~~~~~log~~~~~~~~~~~~~~~
240
360
30
Copy the code
  • To write their ownThe get and setThe property cannot be declared or writtenThe get and setMethod is like living a variable, the variablesetYou can’t assign values to yourself in the method (you get stuck in an infinite recursive state), you can only assign values to other attributes, you can see the results in the example, you can try it yourself

6. Construction methods

Dart’s construction methods vary greatly

  • 6.1 First Dart provides a default empty constructor like Java, but once we implement our own constructor, this default constructor becomes invalid and our own written constructor replaces the default constructor. Dart also provides handy syntactic sugar
class Book {
  var name, age;
    
  // Standard notation
  Book(var name, var age){
    this.name = name;
    this.age = age;
   }
  
  // Grammar sugar 1
  Book(this.name, this.age){
   }
  
   // Grammar sugar 2
   Book(this.name, this.age);
}
Copy the code

To be clear, in such constructors, the assignment to this is performed before the body of the constructor

  • 6.2 Dart doesn’t support overloading, so Dart doesNamed constructor, it isClass name + method nameThe way to implement multiple constructors
class Book {
  var name, age;

  Book(this.name, this.age);
  Book.withName(this.name);
  Book.withAge(this.age);
}
Copy the code

The autoprompt can then show that there are multiple constructors

  • 6.3 Constant constructors. If there is an object whose value does not need to change, we can use the constant constructor to construct a constant. If there is an object whose value does not need to change, we can use the constant constructor
// Const objects require that their properties be immutable, i.e. final
class Book {
  final name, age;

  const Book(this.name, this.age);
}

void main() {
  const book = const Book(12.112);
}
Copy the code
  • 6.4 Factory construction method, add before common construction methodfactoryKeyword, which is used with private constructors. Look at the following example
class Book {
  var name, age;

  factory Book(var name){
    return Book._withName(name);
  }

  // Private constructor
  Book._withName(this.name);

  Book._withAge(this.age);

}
Copy the code
  • Dart allows us to declare final as null, but it must be initialized before the code is run. This is the constructor. There are two ways to do this:

Method 1: Assign a value to final after the constructor

class Book {
  var name, age;

  final title;

  Book(this.name, this.age, var title) : this.title = title {}

}
Copy the code

Method 2: Assign directly to the constructor, taking advantage of the feature that this.xxx executes before the body of the method

class Book {
  var name, age;

  final title;

  Book(this.name, this.age, this.title);
}
Copy the code
  • 6.6 objectcallMethods, high level languages allow you to use methods as objects, Dart allows you to use objects as methodsbook1(), which essentially calls the specified method in Book1call
class Book {
  var name, age;

  final title;

  Book(this.name, this.age, this.title);

  call( var value ){
    print("$name asks $value to speak on the stage."); }}void main() {
  var book1 = Book("AA".12."CC");
  var book2 = Book("AA".12."CC");

  book1("PP"); } ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ the log ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ AA class PP students came to power speech, pleaseCopy the code

In fact, all the ++,– and so on are used in this way, but I don’t recommend this, because it will blur the boundary between objects and methods, so the code is hard to read, okay

  • 6.7 Overloading your own constructor

First of all, overloading is not allowed in Dart, but sometimes we have a lot of constructors depending on the situation, so there’s a unified base constructor, and the other constructors use that base constructor depending on the situation

In this case, you can just write the constructor, and the rest is useless

class FreeSlideTransition extends AnimatedWidget {

  Animation<Offset> animation;
  var child;
  Offset begin;
  Offset end;
  FreeSlideTransitionMode type;

  // The constructor's polymorphisms are a bit cumbersome to write and look like
  FreeSlideTransition(this.type, this.child,
      {Key key, Animation<double> animation, Offset begin, Offset end})
      : super(key: key, listenable: animation) {
    this.animation = Tween<Offset>(begin: begin, end: end).animate(animation);
  }

  FreeSlideTransition.reverseX(
      {Widget child,
      Animation<double> animation,
      Key key,
      Offset begin,
      Offset end})
      : this(FreeSlideTransitionMode.reverseX, child,
            key: key, animation: animation, begin: begin, end: end);

  FreeSlideTransition.reverseY(
      {Widget child,
      Animation<double> animation,
      Key key,
      Offset begin,
      Offset end})
      : this(FreeSlideTransitionMode.reverseY, child,
            key: key, animation: animation, begin: begin, end: end);
}
Copy the code

7 inherited

Dart is a single inheritance, and a child class cannot inherit the parent class’s private (property, method) and constructor

Dart’s subclass defaults to its parent class’s default constructor. If the parent class does not have a default constructor, it must display one of its parent class’s constructors. See the following example:

class Animal {
  var name, sex;

  Animal(this.name);

  Animal.withSex(this.sex);
}

class Dog extends Animal {
  Dog(name) : super(name);

  Dog.withSex(sex) : super.withSex(sex);
}
Copy the code

And what makes things a little bit more complicated is adding a final assignment, which is associated in between

class Dog extends Animal {
  final price;

  Dog.withSex(var sex, var price)
      : this.price = price,
        super.withSex(sex);
}
Copy the code

8. Multiple inheritance

Dart has a word for multiple inheritance: Mixins. Dart allows you to implement multiple inheritance using the with keyword, but multiple inheritance itself is very dangerous and can cause problems

Standard writing:

class Animal {
  var age, sex;
}

class Cat {
  var name;

  speak() {
    print("CAT"); }}class Dog {
  var name;

  speak() {
    print("DOG"); }}class Bear {
  var name;

  speak() {
    print("BEAR"); }}class MyPet extends Animal with Dog.Cat.Bear {
  var n;

  MyPet(this.n);
}
Copy the code

Then let’s call pet.speak() to see

  var pet = MyPet();
  pet.speak();
  
  ~~~~~~~~log~~~~~~~~
  BEAR
Copy the code

This means that for multiple inheritance, attributes and methods with the same name from multiple parent classes are based on the data of the last parent class inherited

And multiple inheritance is very strict on the superclass requirements, requires that the superclass must not have its own constructor, except for the default… Egg pain is not, and more inheritance is easy to problem, use should pay special attention to

Multiple inheritance is further composed, for the combination of functions between modules and within the architecture. Look at the following code, which I have no experience with, also hearsay

class MyPet1 = Animal with Dog;
class MyPet2 = Animal with Cat;
class MyPet3 = Animal with Bear;
Copy the code

I have three pets with different functions. Note that this requires subclasses like MyPet1 not to have their own properties and methods. This is purely for the purpose of combining functions

9. An abstract class

Dart’s abstract class does not use the abstract keyword. Dart’s abstract class is thought to be more like an interface

abstract class Cat{
  void speak();
}
Copy the code

Interface of 10.

Dart has no interfaces. In Dart, interfaces are objects. You can directly inherit an object with the implements keyword, but all the properties and methods in that object need to be overwrite

class Animal {
  var name, sex;

  Animal(this.name);

  Animal.withSex(this.sex);
}

class Dog implements Animal {
  @override
  var name;

  @override
  var sex;
}
Copy the code

This is where the importance of abstract classes comes in. In Dart, we usually write interfaces as abstract classes

abstract class Cat{
  void speak();
}

class Dog implements Cat {
  @override
  void speak() {
    // TODO: implement speak}}Copy the code

11. A Mixin

Dart implements are quite limited. For example, if you inherit an interface from Dart, you must override all properties and methods in that interface, whether the method is abstract or not

abstract class A {
  runA();

  speakA() {}
}

abstract class B {
  runB();
}

class AA implements A.B {
  @override
  runA() {
    // TODO: implement runA
    return null;
  }

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

  @override
  speakA() {
    // TODO: implement speakA
    return null; }}Copy the code

This is obviously too restrictive and uncomfortable to use in many cases, so Dart provides a new interface type: mixins. After you implement mixins, you can implement the interface just like Java, using: with

mixin A {
  runA();

  speakA() {}
}

mixin B {
  runB();
}

class AA with A.B {
  @override
  runA() {
    // TODO: implement runA
    return null;
  }

  @override
  runB() {
    // TODO: implement runB
    return null; }}Copy the code

12. Override operators

This is a SAO operation, which will make our code look very nice, what are the operators: +,-,++,> and these are, we can use the operator keyword + inside the class to add operations such as +,-,++,> to our object

class Book{
  var price;
  var _name = "AA";

  Book(this.price);

  operator >( Book otherBook ){
    return this.price > otherBook.price;
  }

  operator[] (String attribute){
    switch(attribute){
      case "price": {returnprice; }break;
      case "name": {return_name; }break;
      default: {return null; }}}}void main() {

  var book1 = Book(20);
  var book2 = Book(30);

  print( book1 > book2 );
  print( book1["price"]);print( book1["name"]); }Copy the code

Book1 [“price”] this allows us to call the property of the object in a different way, so you can get the private property of the object from the outside


The generic

Generics in Dart are similar to JAVA syntax

1. Use generics in classes

class Location {
  Object x;
  Object y;

  Location(this.x, this.y);
}
Copy the code

2. Use generics in methods

class Location<T> {
  T x;
  T y;

  Location(this.x, this.y);
}
Copy the code

3. Use generics in collections

  • 3.1 the list
// Do not use generics to restrict data types
var names = ['aa'.'bb'.'cc'.111];

// After using generics
var names = <String> ['aa'.'bb'.'cc'];
Copy the code
  • 3.2 the map
// Do not use generics to restrict data types
var infos = {1: 'one'.'name': 'why'.'age': 18}; 

// After using generics
Map<String.String> infos = {'name': 'why'.'age': '18'};
Copy the code

The introduction of the library

In front of a simple guide library, here let’s talk in detail

1. Three methods of Dart guide library:

  • The Dart standard library– These libraries are built into Dart, such as:Dart: IO, dart: HTML, dart:math
import 'dart:io';
Copy the code
  • Pub package manager– Use prefixes:package:Packages such as Flutter are imported using the Pub manager
import 'package:flutter/material.dart';
Copy the code
  • The specified path– Can be a relative path or an absolute path
import 'lib/student/student.dart';
Copy the code

2. Keywords show, hide, and as

  • show– Import only the specified file
  • hide– Hide the specified file and import everything else
  • as– names
import 'lib/student/student.dart' show Student, Person;
import 'lib/student/student.dart' hide Person;
import 'lib/student/student.dart' as Stu;

// Use the use of alias
Stu.Student s = new Stu.Student();
Copy the code

This is exactly the same as with Python

3. The library, the part

If you don’t have a name for a library, you can’t use a library without a name. And then when the library is too big to fit in one file, part comes into play. You can use part to associate sub-files into the main file of the library

How to use:

  • Subfile usagePart of "name"To associate the library master file
  • Library master file usedThe subfilename.dartTo bind a subfile to the library

Master file AB. The dart

library AB
part "mathUtils.dart";
part "dateUtils.dart";
Copy the code

Son file mathUtils. Dart

part of "AB.dart";

int sum(int num1, int num2) {
  return num1 + num2;
}
Copy the code

Well, some trouble, need to subfile and main file declaration each other, a little convoluted, first start will be very confusing, but all unreasonable will be eliminated, this thing is outdated now

4. Export definition libraries

Export is used in place of path. In the days of export, we only needed to declare the subfiles in the main library file, so we didn’t have to worry about the subfiles

Master file AB. The dart

library AB;

export "mathUtils.dart";
export "dateUtils.dart";
Copy the code

Son file mathUtils. Dart

int sum(int num1, int num2) {
  return num1 + num2;
}
Copy the code

5. Load the library lazily

The lazy loading of library is quite strange, WHICH is the first time I have encountered such a design. The scene mainly has the following points:

  • Reduce the initial startup time of the APP
  • Perform A/B tests, such as trying different implementations of various algorithms
  • Load rarely used features

To lazily load a library, import it using eferred as:

import 'package:deferred/hello.dart' deferred as hello;
Copy the code

Copy the code when needed, call the loadLibrary() function to load the library:

greet() async {
  await hello.loadLibrary();
  hello.printGreeting();
}
Copy the code