This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money.

Preface: Recently, when I was helping some friends to fix bugs, THERE were always some strange problems (I was completely confused to tell you the truth). After careful investigation, I found that the syntax of Flutter was wrong. When I first started Flutter, I found that Dart grammar was similar to Java, so I didn’t study Dart grammar carefully. Now this foundation is not solid disadvantages reflected 😖

(This article is recommended for programmers using Js and Dart, as both are single-threaded languages.)

It’s important to understand what asynchrony is!!

Simple explanation:

Synchronization generally refers to the sequence of execution between two tasks

Asynchronous generally refers to doing more than one thing at the same time (I asked you the following picture image 👍)

Some common asynchronous operations:

1) Network request

2) When writing to the database

3) When reading data from a file

Asynchrony in Dart

Here we are given two ways to implement asynchronous logic

Official:

  • Stream
  • Future

Here we go into detail about Future

The use of the Future

Common Future constructors:

So the code can all be run here: dartpad.dev/

New Future((){// write business code here});Copy the code

Of course, there are divide-and-conquer tasks, which require a large task to be broken up into many smaller tasks to be executed step by step. The future. then function is used to break down tasks

Then ((a) => "return :$a") // Subtask after task execution. Then ((a) => A.length) // where a is the result returned after last task execution .then((a) => printLength(a)) .whenComplete(() => whenTaskCompelete); // Callback function when all tasks are completed}Copy the code

When a task needs to be delayed, you can use new Future.delay to delay the execution of the task

Future.delayed(const Duration(seconds: 2), () => print(''));
Copy the code

Here’s a simple example:

Void main() {print(' start running '); getUserMessage(); } Future<void> getUserMessage() {// If we are asking for some data return future.delayed (const Duration(seconds: 2), () => print(' get network info '); }Copy the code

The result should be:

Start // Network information is obtained after two secondsCopy the code

useasync-await

This is a syntax for implementing asynchronous logic

Remember two rules:

Keep these two basic principles in mind:

  • To define an asynchronous function, add async before the function body:
  • The await keyword only works in async functions.

Give a simple example based on the synchronization function:

Void main() {print(' start running '); getUserMessage(); } Future<void> getUserMessage() async{ print(await postUserInput()); Return future.delayed (const Duration(seconds: 2), () => print(' get network info ')); Future<String> postUserInput() => future.delayed (const Duration(seconds) : 2), () => 'I sent data ',);Copy the code

The return result is correct:

It's up and running and I'm sending data to get information into the networkCopy the code

But if you don’t use await

 print(postUserInput());
Copy the code

At this point it will print:

Start run Instance of '_Future<String>' to get network informationCopy the code

Why is that?

Resolution:

  • PostUserInput () is an asynchronous function that prints “I sent data” after a delay
  • The right thing to do would be to wait for postUserInput() to finish before requesting data, but no await is used, that is, no string is returned
  • So postUserInput() cannot be described correctly, only that it is an instance of a Future

Assigning this function to a variable will cause an error

String data = postUserInput();
Copy the code

The parsing is the same as above

The order processing

You can use multiple await expressions to ensure that each statement completes before the next statement executes:

Async {await A(); async {await A(); await B(); test(await C()); }Copy the code

Async and await conclusion:

  1. To return await… , so the function is async first
  2. Functions that use async annotation or asynchronous functions must receive the return value with await, such as var data = await postUserInput();

Use then:

Then callback :(don’t want to stop and run the next code block after completing the request function)

Future<R> then <R>(
    FutureOr<R> onValue(
    T value
    ), {
    Function onError
})  
Copy the code

Here’s a simple example:

Void main() {print(' start running '); Future.delayed(Duration(seconds: 1), () {print(' request data '); }). Then ((a) {print(' a'); }); }Copy the code

Output:

Start running request data to get data NULLCopy the code

The difference between then and await

The callback to THEN is similar to the observer mode, the then main purpose is to process the value when the Future completes to avoid blocking, while await suspends the async function it is in, this difference is very important for the stack!!

Handling exception errors

Handling errors in async requires a try

Future<void> printDailyNewsDigest() async { try { var newsDigest = await gatherNewsReports(); print(newsDigest); } catch (e) {// Handle code execution errors... }}Copy the code

Use catchError with whenComplete

Future also has two more commonly used apis,catchError and whenComplete. CatchError is used to catch errors, and whenComplete is called in any case,

WhenComplete (whenComplete) {whenComplete (whenComplete) {whenComplete (whenComplete)

The catchError method is the same as the then method. The catchError method is the same as the then method. The catchError method is the same as the then method. OnError can only handle exceptions for Future objects that call THEN

Future.then((value)=>getUserMessage(value), onError: (e){}).then().catchError();  
Copy the code

In this case, onError can only catch Future exceptions, but catchError can catch Future and getUserMessage exceptions.

The text is not much, but it is summed up by heart, so, brothers give a thumbs up, if there is incomplete or wrong, let me know in the comment section, thanks ~

If you have any questions, please contact me here