iT邦幫忙

2021 iThome 鐵人賽

DAY 22
0
Mobile Development

Flutter with GetX, loading*175%歷程 系列 第 22

[Day22] Flutter GetX with Dio (一)

  • 分享至 

  • xImage
  •  

Dio

Dio是 http request的framework
也可以用內建的HttpClient或是http,
選擇Dio則是覺得簡單好用
還有interceptors攔截.

那廢話不多說 直接上code
用singleton封裝成自己要的class,
這邊叫HttpUtil, server host統一寫在 BASEURL這裡,
可以在request前後,或發生例外狀況時增加攔截,
這邊礙於長度 就只列出get方法,其他的請參考下面附錄的GitHub.


const BASEURL = "https://newsapi.org/v2";

class HttpUtil {
  static final HttpUtil _instance = HttpUtil._internal();
  late Dio dio;

  factory HttpUtil() => _instance;

  HttpUtil._internal() {
    BaseOptions options = BaseOptions();
    options.baseUrl = BASEURL;
    options.receiveTimeout = 10000; 
    options.connectTimeout = 8000; 
    options.contentType = 'application/json';
    dio = Dio(options);

    // 添加攔截
    dio.interceptors.add(InterceptorsWrapper(onRequest: (options, handler) {
      // Do something before request is sent
      handler.next(options);
    }, onResponse: (response, handler) {
      // Do something with response data
      return handler.next(response); // continue
    }, onError: (DioError error, handler) async {
      // Do something with response error
      return handler.next(error);
    }));
  }

  Future get(String path,
      {dynamic params, Options? options, CancelToken? cancelToken}) async {
    try {
      setTokenToOptions();
      var response = await dio.get(path,
          queryParameters: params, cancelToken: cancelToken);
      return response;
    } on DioError catch (e) {
      createErrorEntity(e);
      return e;
    }
  }
}

本篇有參考自對岸貓哥的GitHub

本篇的GitHub source code

下一篇繼續位大家介紹Dio
(fetch News API, JOSN parsing, 與GetX結合)


上一篇
[Day21] Flutter GetX with animation
下一篇
[Day23] Flutter GetX with Dio (二)
系列文
Flutter with GetX, loading*175%歷程 30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言