If you want to learn about Flutter, follow this column, The Flutter series (1), in detail

The Flutter series (II) — contrast with React Native

The Flutter Series (3) — Environment Builder (Windows)

Flutter series 4 — HelloWorld

Dart language Description (1) — Detailed introduction

Dart (2) — Basic syntax

Archive: github.com/yang0range/…

preface

In our last article, we covered the basic syntax of the Dart syntax in detail. In this article, we continue to cover the Dart syntax.

abnormal

Both Java and Dart languages have exceptions and catch exceptions, but Dart exceptions are non-checked exceptions. Methods do not declare exceptions that may be thrown, and do not require any exceptions to be caught.

Dart provides the Exception and Error types and a number of subtypes to define exceptions. However, you can also customize exceptions by throwing non-empty objects as exceptions. They do not have to be Exception and Error objects, but generally they are of the Exception and Error types thrown.

Let’s talk about it in detail.

The Exception types




The Error type




Exception is thrown

Throwing an exception is very similar to Java.

// Throw new FormatException('Format exception'); // throw new NullThrownError(); // throw any non-null object'This is an exception.';

Copy the code

Exception handling

try { throw new NullThrownError(); // throw new OutOfMemoryError(); } on OutOfMemoryError {//on Specifies the exception typeprint('Out of memory'); // rethrow; } on Error {// Catch the Error typeprint('Unknown error catched'); } on Exception catch (e) {// Catch the Exception typeprint('Unknown exception catched'); } catch(e, s) {// Catch () can take one or two arguments, the first argument being the exception object thrown and the second StackTrace object stack informationprint(e);
    print(s); }}Copy the code

class

The concept of a class is similar to that in Java. But there are big differences.

  • The structure of the class
Class P {double x; double y; P(int x, int y) { this.x = x; this.y = y; }} class P {num x; num y; Point(this.x, this.y);Copy the code
  • Redirect constructor
class P { num x; num y; Point(this.x, this.y); P.longxaxis (num x) : this(x, 0); // Redirect constructor to call other constructors with colons. }Copy the code
  • Class Get and Set methods
class Rectangle {
  num left;
  num top;
  num width;
  num height;

  Rectangle(this.left, this.top, this.width, this.height);

  num get right => left + width;
  set right(num value) => left = value - width;
  num get bottom => top + height;
  set bottom(num value) => top = value - height;
}

Copy the code
  • mixins

Mixins are a new concept in Dart that is simply used to reuse code between classes, reducing coupling, in other words, extending methods (or variables) from them without extending classes.

Do not know, a use to find, really sweet!

Here are some specific examples:

For example, we have a career diagram like this:




image.png

The following relationship can be sorted out from the figure:

  • There are software engineers and construction engineers, and they are all engineers in common.
  • There are art teachers and IT teachers, and they all have teachers in common.

If we use Java to implement the flower

// class Worker {public voiddoWork(); } // Engineer extends Worker {@override public voiddoWork() {
        System.out.println("Engineer at work."); } // class Teacher extends Worker {@override public voiddoWork() {
        System.out.println("The teacher is teaching"); }} // class SoftwareEngineer extends Engineer { ArtTeacher extends Teacher {}Copy the code

If YOU use Dart

// class Worker {voiddoWork(); // class Engineer extends Worker {voiddoWork() {
    print('Engineer at work'); } // class Teacher extends Worker {voiddoWork() {
    print('Teacher is teaching'); }} // class SoftwareEngineer extends Engineer { ArtTeacher extends Teacher {}Copy the code

From this point of view, it doesn’t seem that Java and Dart are particularly different because Dart is also single-inherited.

Now, let’s enrich the scene a little bit.




image.png

As can be seen from graphs and tables, software engineers and IT teachers have the ability to repair computers, while architectural engineers and art teachers have the ability to draw by hand. However, these abilities are unique to them and not those of engineers or teachers, so they cannot be realized in their parent class.

If you’re using Java, then interface is a natural choice.

interface CanFixComputer { void fixComputer(); } interface CanDesignSoftware { void designSoftware(); } // class SoftwareEngineer extends Engineer implements CanFixComputer, CanDesignSoftware {@override public voidfixComputer() {
        System.out.println("Fix the computer");
    }

    @Override
    public void designSoftware() {
        System.out.println("Design software"); } //IT Teacher extends Teacher implements CanFixComputer {@override public voidfixComputer() {
        System.out.println("Fix the computer"); }}Copy the code

But just because Dart doesn’t have an interface doesn’t mean Dart doesn’t have an interface. In fact, any class in Dart is an interface, and you can implement any class by overriding all the specific methods in that class.

If you want to implement this with Dart, you just need to change the interface to abstract Class.

However, we found that the fixComputer interface was inherited twice, and the implementation was the same both times, which caused the problem of code duplication and redundancy. What to do? In Java, we have a default implementation of the interface to solve this problem (a last resort for Java 8).

But with mixins, it’s not so hard.

abstract class CanFixComputer {
  void fixComputer() {
    print('Fix the computer');
  }
}

abstract class CanDesignSoftware {
  void designSoftware() {
    print('Design software'); }} class SoftwareEngineer extends Engineer with CanFixComputer, CanDesignSoftware {} extends Teacher with CanFixComputer {}main() {
  ITTeacher itTeacher = new ITTeacher();
  itTeacher.doWork();
  itTeacher.fixComputer();
  SoftwareEngineer softwareEngineer = new SoftwareEngineer();
  softwareEngineer.doWork();
  softwareEngineer.fixComputer();
  softwareEngineer.designSoftware();
}
Copy the code

From the above code, we can see that there is no implements, nor extends, but with.

Each class with a particular feature no longer needs to specifically implement the same function. Interfaces cannot implement functions. Although functions can be implemented through inheritance, there is already a parent class, which is not a parent class, and multiple inheritance is not allowed. The development layer only needs to be concerned with what features are currently needed, while the development function module is concerned with what functions to achieve.

Understanding the order

With, with, with, with

class First {
  void doPrint() {
    print('First');
  }
}

class Second {
  void doPrint() {
    print('Second');
  }
}

class Father {
  void doPrint() {
    print('Father');
  }
}

class Son1 extends Father with First,Second {
  void doPrint() {
    print('Son1');
  }
}

class Son2 extends Father with First implements Second {
  void doPrint() {
    print('Son2'); }}main() {
  Son1 son1 = new Son1();
  son1.doPrint();
  Son2 son2 = new Son2();
  son2.doPrint();
}
Copy the code

The output is:

Son1
Son2
Copy the code

From here, you can see that the highest priority, whether extends, implements, or mixin, is the method in the concrete class.

Next example:

class First {
  void doPrint() {
    print('First');
  }
}

class Second {
  void doPrint() {
    print('Second');
  }
}

class Father {
  void doPrint() {
    print('Father');
  }
}

class Son1 extends Father with First,Second {

}

class Son2 extends Father with First implements Second {

}

main() {
  Son1 son1 = new Son1();
  son1.doPrint();
  Son2 son2 = new Son2();
  son2.doPrint();
}
Copy the code

Output results:

Second
First
Copy the code

Son2 implements the doPrint() method, which implements First Mixin. The order of mixins can also be looked at backwards from the code, with the mixins having the highest precedence.

The generic

In Dart, there are many container objects, and you can define generic types when creating objects, just like in Java. Such as:

 var list = List<String>();
  list.add('aaa');
  list.add('bbb');
  list.add('ccc');
  print(list);

  var map = Map<int, String>();
  map[1] = 'aaaa';
  map[2] = 'bbbb';
  map[3] = 'cccc';
  print(map);
Copy the code

The difference with Java

Generics information in Java is compile-time; generics information does not exist at run time.

Dart’s generic types are hardwired and determinable at run time.

asynchronous

Future

We can’t talk about asynchrony without talking about Future.

A Future, much like a Promise in JavaScript, represents the final completion (or failure) of an asynchronous operation and the representation of its resulting value. In simple terms, it is used to handle asynchronous operations, executing the successful operation if the asynchronous process succeeds, and catching errors or stopping subsequent operations if the asynchronous process fails. A Future only has one outcome, either success or failure.

Because a Flutter returns a Fluter object, the chain approach is natural.

  1. Future.then Subtask after the task is executed
  2. Future.delayed execution
  3. Future.catcherror If an error occurs in an asynchronous task, we can catch the error in a catchError.
  4. Called when future. whenComplete is complete.
  5. Future.wait waits for multiple asynchronous tasks to complete before performing operations.

Async/await

If the business logic has a large number of asynchronous dependencies, the above situation will occur within the Callback, too much nesting can lead to code readable and error rate, and very difficult to maintain, this problem is known as Callback Hell.

This problem is very prominent in JS, Dart is almost the same problem, and then shift the relevant method over. So the functionality and usage are almost the same.

  • Async is used to indicate that a function is asynchronous. The defined function returns a Future object. Callbacks can be added using the then method.
  • “Await” is followed by a Future, which means to wait for the asynchronous task to complete and then proceed. Await must appear inside async function.

Only async methods can call methods using the await keyword

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

Stream

A Stream is also used to receive asynchronous event data and, unlike a Future, can receive the results (success or failure) of multiple asynchronous operations. That is, success or failure events can be fired multiple times to pass result data or error exceptions while performing an asynchronous task. Stream is commonly used in asynchronous task scenarios where data is read multiple times, such as network content download and file read and write.

Future.delayed(new Duration(seconds: 1), () {return "hello 1"; }), // throw an exception future.delayed (new Duration(seconds: 2),(){throw AssertionError()"Error"); }), // future.delayed (new Duration(seconds: 3), () {return "hello 3";
  })
]).listen((data){
   print(data);
}, onError: (e){
   print(e.message);
},onDone: (){

});
Copy the code

The output

I/flutter (17666): hello 1
I/flutter (17666): Error
I/flutter (17666): hello 3
Copy the code

Isolates – isolation

All Dart code runs in a quarantine zone, not a thread. Each quarantine has its own memory heap, ensuring that the quarantine’s state is not accessed from any other quarantine.

The last

In these three articles, we’ve basically covered what the Dart language is all about.

These are more theoretical, grammar is still in the process of more practice, more writing, more practice to find the true meaning of it.

Next, we will introduce Flutter in detail! Flutter has been one of the Top20 software libraries. Through the next series of articles, I hope that we can learn Flutter together, make progress together, gain something together, and master the initiative of the future technology mainstream!

Have any good suggestion, opinion, idea welcome to leave a message to me!

Welcome to pay attention to the public number

Pay attention to the public number will have more harvest!




image.png




Move a small hand to praise, collect, forward a key three even go a wave!

Reference documentation

Kevinwu. Cn/p/ae2ce64 / www.jianshu.com/p/06604077d… The Real Flutter