Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Dart Asynchronous Programming

Dart Asynchronous Programming

Asynchronous programming is one of the most core capabilities in modern application development.

Whether it is network requests, file reads/writes, or database operations, asynchronous handling is needed to avoid blocking the main thread.

This chapter introduces the concept of Future, the async/await syntax, and how to handle asynchronous errors.


Why Asynchronous Programming Is Needed

First understand the difference between synchronous and asynchronous.

Synchronous code executes line by line in order; the next line will not start until the previous line finishes.

If an operation needs to wait (such as a network request), the entire program gets stuck.

Example

Compare the execution effect of synchronous and asynchronous code:

// Simulate a time-consuming operation

String fetchDataSync

(

)

{

 

// Synchronous code: suppose we need to wait 2 seconds here

 

// During these 2 seconds, the whole program can do nothing

  sleep

(

Duration

(

seconds

:

2

)

)

;

 

// Blocking wait

 

return

'Data fetch complete'

;

}

// Asynchronous version: does not block the main thread

Future

<

String

fetchDataAsync

(

)

async

{

// Asynchronous wait: during these 2 seconds the program can continue other tasks

  await Future.

delayed

(

Duration

(

seconds

:

2

)

)

;

 

return

'Data fetch complete'

;

}

void

main

(

)

async

{

  print

(

'Start fetching data synchronously...'

)

;

 

var

syncResult

=

fetchDataSync

(

)

;

  print

(

'Synchronous result: $syncResult'

)

;

  print

(

'(Note: the program is stuck during synchronous execution)'

)

;

  print

(

'\nStart fetching data asynchronously...'

)

;

  print

(

'After issuing the request, the program continues with other tasks...'

)

;

 

var

asyncResult

=

await fetchDataAsync

(

)

;

  print

(

'Asynchronous result: $asyncResult'

)

;

  print

(

'(The program is not stuck during asynchronous execution)'

)

;

}



开始同步获取数据...

同步结果: 数据获取完成

(注意:同步期间程序被卡住了)



开始异步获取数据...

发起请求后,程序继续执行其他任务...

异步结果: 数据获取完成

(异步期间程序没有被卡住)

In Dart, all I/O operations (file, network, database) should use the asynchronous approach. Synchronous I/O blocks the entire Isolate and causes UI jank in Flutter apps.


The Concept of Future

Future Represents a value that "will complete at some point in the future".

It is like a promise: I have no result now, but I will definitely give you a value of type T (or an error) in the future.

A Future has three states:

State Description
Uncompleted The asynchronous operation is still in progress
Completed with data The operation succeeded and the Future carries a result value
Completed with error The operation failed and the Future carries error information

Example

Creating and using a Future:

void

main

(

)

{

  print

(

'Program starts'

)

;

 

// Create a Future

  Future

<

String

future

=

Future

(

(

)

{

// This function will execute at some point in the future

   

return

'RUNOOB async result'

;

 

}

)

;

  print

(

'Future created, but not yet completed'

)

;

 

// Register a callback: executed when the Future completes

  future.

then

(

(

result

)

{

    print

(

'Received result: $result'

)

;

 

}

)

;

  print

(

'Program continues...'

)

;

}



程序开始

Future 已创建,但还没完成

程序继续执行...

收到结果: RUNOOB 异步结果

Note the output order: "Program continues" is printed first, then "Received result".

This shows that the Future callback executes asynchronously and does not block subsequent code.


async / await Syntax

async and await are the core syntax for handling asynchronous operations in Dart.

async marks a function as asynchronous; await waits for a Future to complete and retrieves its result.

Example

// The async keyword marks a function as asynchronous

// The return type of an async function must be Future

Future

<

String

fetchUserName

(

int

id

)

async

{

// await waits for the Future to complete and gets its value

 

// During the wait, the current function pauses but does not block other code

  await Future.

delayed

(

Duration

(

seconds

:

1

)

)

;

 

return

'User $id'

;

}

Future

<

int

fetchUserAge

(

int

id

)

async

{

  await Future.

delayed

(

Duration

(

milliseconds

:

500

)

)

;

 

return

20

id

;

}

// Execute multiple asynchronous operations sequentially

Future

<

void

printUserInfo

(

int

id

)

async

{

print

(

'Start fetching user info...'

)

;

 

// Wait one by one: first get the name, then the age

 

var

name

=

await fetchUserName

(

id

)

;

  print

(

'Got name: $name'

)

;

 

var

age

=

await fetchUserAge

(

id

)

;

  print

(

'Got age: $age'

)

;

  print

(

'RUNOOB user: $name, age: $age'

)

;

}

// Execute multiple asynchronous operations concurrently

Future

<

void

printUserInfoParallel

(

int

id

)

async

{

print

(

'Start fetching user info concurrently...'

)

;

 

// Issue two requests at the same time without waiting for each other

 

var

nameFuture

=

fetchUserName

(

id

)

;

 

var

ageFuture

=

fetchUserAge

(

id

)

;

 

// Wait for both requests to complete

 

var

results

=

await Future.

wait

(

[

nameFuture

,

ageFuture

]

)

;

 

var

name

=

results

[

0

]

as

String

;

 

var

age

=

results

[

1

]

as

int

;

  print

(

'RUNOOB user (concurrent): $name, age: $age'

)

;

}

void

main

(

)

async

{

 

// Sequential execution (total time ~ 1s + 0.5s = 1.5s)

  await printUserInfo

(

1

)

;

  print

(

'---'

)

;

 

// Concurrent execution (total time ~ max(1s, 0.5s) = 1s)

  await printUserInfoParallel

(

2

)

;

}



开始获取用户信息...

获取到名称: 用户1

获取到年龄: 21

RUNOOB 用户: 用户1, 年龄: 21

---

开始并发获取用户信息...

RUNOOB 用户(并发): 用户2, 年龄: 22

If there is no dependency between multiple asynchronous operations, you should use Future.wait to make them run concurrently instead of awaiting one by one. This significantly improves performance - the total time equals the slowest operation, not the sum of all operations.

Core Rules of async/await

Rule Description
An async function returns a Future Even if the function returns T, async automatically wraps it into a Future
await can only be used inside an async function A normal function cannot use await
await pauses the current function But does not block the execution of other code
await retrieves the Future's result If the Future has an error, await throws an exception

then / catchError Chaining

Besides async/await, Dart also supports chaining with then() and catchError().

This is the traditional Promise-style approach.

Example

// Function that simulates a network request

Future

<

String

fetchData

(

String url

)

{

 

return

Future.

delayed

(

Duration

(

seconds

:

1

)

,

(

)

{

   

if

(

url.

isEmpty

)

{

     

throw

Exception

(

'URL cannot be empty'

)

;

   

}

   

return

'Data from $url'

;

 

}

)

;

}

void

main

(

)

{

  print

(

'Start request...'

)

;

 

// then / catchError chaining

  fetchData

(

'https://runoob.com/api'

)

      .

then

(

(

data

)

{

       

// Request succeeded

        print

(

'Got data: $data'

)

;

       

return

'Processed: $data'

;

 

// The return value is passed to the next then

     

}

)

      .

then

(

(

processed

)

{

       

// Handle the return value of the previous then

        print

(

processed

)

;

     

}

)

      .

catchError

(

(

error

)

{

       

// Uniformly catch any error in the chain

        print

(

'Request error: $error'

)

;

     

}

)

      .

whenComplete

(

(

)

{

       

// Executes whether success or failure (similar to finally)

        print

(

'Request finished (whether success or failure)'

)

;

     

}

)

;

  print

(

'Request sent, program continues...'

)

;

}



开始请求...

请求已发出,程序继续...

获取到数据: 来自 https://runoob.com/api 的数据

处理后的: 来自 https://runoob.com/api 的数据

请求结束(无论成功或失败)

How to Choose Between async/await and then/catchError

Scenario Recommended approach Reason
Linear asynchronous flow async/await Code is as clear as synchronous code
Multiple concurrent requests async/await + Future.wait Semantically clear
Chained data transformation then() Each then does one transformation, the chain is clear
Single callback then() More concise than async/await

In most cases async/await is recommended because it is more readable. But then() is still valuable for simple chained processing. The two can be mixed, but it is not recommended - a function should use either async/await or then/catchError; mixing makes the code hard to understand.


Handling Asynchronous Errors

Errors may occur in asynchronous operations and need to be handled with try-catch.

async/await makes error handling as simple as with synchronous code.

Example

// Simulate a network request that may fail

Future

<

String

fetchUserProfile

(

int

userId

)

async

{

  await Future.

delayed

(

Duration

(

seconds

:

1

)

)

;

 

if

(

userId

<=

0

)

{

   

throw

Exception

(

'Invalid user ID: $userId'

)

;

 

}

 

if

(

userId

==

404

)

{

   

throw

HttpException

(

'User does not exist'

)

;

 

}

 

return

'Profile of user $userId'

;

}

// Custom exception

class

HttpException

implements

Exception

{

 

final

String message

;

  HttpException

(

this

.

message

)

;

  @override

  String toString

(

)

=>

'HttpException: $message'

;

}

Future

<

void

loadUserProfile

(

int

userId

)

async

{

print

(

'Loading profile of user $userId...'

)

;

 

try

{

   

var

profile

=

await fetchUserProfile

(

userId

)

;

    print

(

'Loaded successfully: $profile'

)

;

 

}

on HttpException

catch

(

e

)

{

   

// Catch specific asynchronous errors by type

    print

(

'HTTP error: $e'

)

;

    print

(

'Prompt the user: please check whether the user exists'

)

;

 

}

on Exception

catch

(

e

)

{

   

// Catch other exceptions

    print

(

'General error: $e'

)

;

 

}

finally

{

    print

(

'Loading operation finished'

)

;

 

}

}

void

main

(

)

async

{

  await loadUserProfile

(

1

)

;

   

// Success

  print

(

'---'

)

;

  await loadUserProfile

(

404

)

;

 

// HttpException

  print

(

'---'

)

;

  await loadUserProfile

(

1

)

;

 

// General Exception

}



正在加载用户 1 的资料...

加载成功: 用户 1 的个人资料

加载操作结束

---

正在加载用户 404 的资料...

HTTP 错误: HttpException: 用户不存在

提示用户:请检查用户是否存在

加载操作结束

---

正在加载用户 -1 的资料...

一般错误: Exception: 无效的用户 ID: -1

加载操作结束

Error handling rules in async functions:

Never ignore asynchronous errors. Every async function call should have corresponding error handling. Unhandled asynchronous errors print warnings in development mode and may be silently ignored in production, leading to bugs that are hard to track down.