Dart 异步

2022/11/14 Dart基础

本文介绍Dart异步的处理方法,并且介绍了语法糖的使用方法。

# 异步回调then







  •  




    import 'package:dio/dio.dart';
    
    void main() async {
      final dio = Dio();
      const url = "https://wpapi.ducafecat.tech/products/categories";
    
      dio.get(url).then((response) {
        print(response.data);
      });
    }
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10

# 语法糖await







  •  



    import 'package:dio/dio.dart';
    
    void main() async {
      final dio = Dio();
      const url = "https://wpapi.ducafecat.tech/products/categories";
    
      Response<String> response = await dio.get(url);
      print(response);
    }
    
    1
    2
    3
    4
    5
    6
    7
    8
    9

# 异步返回值

定义 Future<T> 返回对象;




  •  





    // dart_learn
    import 'package:dio/dio.dart';
    
    Future<String?> getUrl(String url) async {
      final dio = Dio();
      Response<String> response = await dio.get(url);
      return response.data;
    }
    
    1
    2
    3
    4
    5
    6
    7
    8
  • import 'package:dart_learn/dart_learn.dart';
    
    void main() async {
      const url = "https://wpapi.ducafecat.tech/products/categories";
    
      var res = await getUrl(url);
      print(res);
    }
    
    1
    2
    3
    4
    5
    6
    7
    8
最后更新时间: 2022/11/29 10:59:07