Dart:二十六、异步 async

异步 async

异步回调 then

import 'package:dio/dio.dart';

void main() {
  Dio dio = Dio();
  dio.get("https://wpapi.ducafecat.tech/products/categories").then((response) {
    print(response.data);
  });
}

[{id: 34, name: Bag, slug: bag, parent: 0, description: ...

then 的方式异步回调

异步等待 await

import 'package:dio/dio.dart';

void main() async {
  Dio dio = Dio();
  Response<String> response =
      await dio.get("https://wpapi.ducafecat.tech/products/categories");
  print(response.data);
}

[{id: 34, name: Bag, slug: bag, parent: 0, description: ...

async 写在函数定义
await 写在异步请求头

异步返回值

import 'package:dio/dio.dart';

Future<String?> getUrl(String url) async {
  Dio dio = Dio();
  Response<String> response = await dio.get(url);
  return response.data;
}

void main() async {
  var content =
      await getUrl('https://wpapi.ducafecat.tech/products/categories');
  print(content);
}

[{id: 34, name: Bag, slug: bag, parent: 0, description: ...

定义 Future<T> 返回对象

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容