:::

6-4 使用dio來取得API資料

  1. 先編輯 pubspec.yaml,安裝 https://pub.dev/packages/dio,並執行 pub get
    dependencies:
      flutter:
        sdk: flutter
    
    
      # The following adds the Cupertino Icons font to your application.
      # Use with the CupertinoIcons class for iOS style icons.
      cupertino_icons: ^1.0.2
      dio: ^3.0.10

     

  2. 引入該套件
    import 'package:dio/dio.dart';

     

  3. 使用之
    Future<Response> getCountriesData() async {
      Response res;
      try {
        res = await Dio().get("https://corona.lmao.ninja/v3/covid-19/countries");
        if (res.statusCode == 200 && res.data != null) {
          return res;
        }
      } on DioError catch (e) {
        print('Dio error: ${e}');
      } catch (e) {
        print('Other error: ${e}');
      }
      return res;
      // //若Widget已經掛載
      // if (mounted) {
      //   //改變狀態
      //   setState(() {});
      // }
    }

     

  4. 或是用state
    Map allData = {};
    
    Future<Response> getData() async {
      try {
        Response res = await Dio().get("https://corona.lmao.ninja/v2/all");
        if (res.statusCode == 200 && res.data != null) {
          allData = res.data;
          // print(res);
        }
      } on DioError catch (e) {
        print('Dio error: ${e}');
      } catch (e) {
        print('Other error: ${e}');
      }
    
      //若Widget已經掛載
      if (mounted) {
        //改變狀態
        setState(() {});
      }
    }
    
    //State狀態初始化
    @override
    void initState() {
      // 要先做父類的State狀態初始化
      super.initState();
      //再做自己的事,如取得資料
      getData();
    }

     


:::

書籍目錄

展開 | 闔起

https%3A%2F%2Fcampus-xoops.tn.edu.tw%2Fmodules%2Ftad_book3%2Fpage.php%3Ftbsn%3D42%26tbdsn%3D1888

計數器

今天: 2217221722172217
昨天: 4038403840384038
總計: 5566180556618055661805566180556618055661805566180