Dart 异步函数

2023/6/1

# Dart 异步函数

在 JavaScript 中,异步调用通过 Promise 来实现,并且实现了 async await 语法糖(async 函数返回一个 Promise,await 用于等待 Promise)。

Dart 中,异步调用通过 Future 来实现。并且也可以使用 async await(async 函数返回一个 Future,await 用于等待 Future)。

import "package:http/http.dart" as http;
import "dart:convert";

Future getIPAddress() {
  final url = 'https://httpbin.org/ip'; // 返回 IP 地址
  return http.get(Uri.parse(url)).then((res) {
    String ip = jsonDecode(res.body)['origin'];
    return ip;
  });
}

void main() {
  // 调用 getIPAddress
  getIPAddress()
    .then((ip) {
      print(ip);
    })
    .catchError((error) {
      print(error);
    });
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

async await 的用法:

import "package:http/http.dart" as http;
import "dart:convert";

Future getIPAddress() async {
  final url = 'https://httpbin.org/ip';
  final res = await http.get(Uri.parse(url));
  String ip = jsonDecode(res.body)['origin'];
  return ip;
}

void main() async {
  // 调用 getIPAddress
  try {
    final ip = await getIPAddress();
    print(ip);
  } catch (error) {
    print(error);
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19