Synchronized methods

Dart is typically executed single-threaded:

  String method1() {
    return "1";
  }

  String method2() {
    return "2";
  }

  String method3() {
    return "3";
  }

  void testA() {
    print(method1());
    print(method2());
    print(method3());
  }
Copy the code

The output:

1
2
3
Copy the code
Asynchronous methods

If you are executing a network request, accessing a database or a file, etc., then the method does not return results immediately and takes some time to execute. You can’t wait for a long time, you’ll get ANR. In this case, we can use Future to describe Future outcomes. Such as:

// Assume that method1 is a network request Future<String> f1 = new Future(method1); Then f1.then((String value) {print("value1=$value"); });Copy the code
Async and await operate asynchronous methods as synchronous methods
  • Async describes a method that performs asynchronous operations
  • Await means to wait for an asynchronous method to return the result before continuing

Such as:

  Future<String> method5() async {
    return "5";
  }
  void testD() async {
    method1();
    String f5 = await method5();
    print(f5);
    method3();
  }
Copy the code

Results:

5 3 1Copy the code
Wait parallel execution

Execute multiple network requests at the same time, wait until all results are returned, and return the result set of a List. Such as:

Future<String> method5() async {
    return "5";
  }

  Future<String> method6() async {
    return "6";
  }

  Future<String> method7() async {
    return "7";
  }

void testE() {
    Future.wait([method5(), method6(), method7()]).then((List responses) {
      print(responses);
    }).catchError((e) {
      print(e);
    });
  }
Copy the code

Results:

[5, 6]Copy the code
Chain calls

Multiple network requests, the latter requiring the return value of the former as an argument, and the last one being the desired value. Such as:

  Future<int> method8() async {
    return 8;
  }

  Future<int> method9(int p) async {
    return p+9;
  }

  Future<int> method10(int p) async {
    return p+10;
  }

void testG() {
    method8().then((value8) {
      print("value8=$value8");
      return method9(value8);
    }).then((value9) {
      print("value9=$value9");
      return method10(value9);
    }).then((value10) {
      print("value10=$value10");
    });
  }
Copy the code

Results:

value8=8
value9=17
value10=27
Copy the code