溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Flutter網(wǎng)絡(luò)請求Dio庫的使用及封裝方法

發(fā)布時間:2022-04-14 13:39:57 來源:億速云 閱讀:1227 作者:iii 欄目:開發(fā)技術(shù)

這篇文章主要講解了“Flutter網(wǎng)絡(luò)請求Dio庫的使用及封裝方法”,文中的講解內(nèi)容簡單清晰,易于學(xué)習(xí)與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學(xué)習(xí)“Flutter網(wǎng)絡(luò)請求Dio庫的使用及封裝方法”吧!

Dart語言內(nèi)置的HttpClient實(shí)現(xiàn)了基本的網(wǎng)絡(luò)請求相關(guān)的操作。但HttpClient本身功能較弱,很多網(wǎng)絡(luò)請求常用功能都不支持,因此在實(shí)際項(xiàng)目中,我們更多是使用dio庫實(shí)現(xiàn)網(wǎng)絡(luò)請求。

注:Flutter官網(wǎng)同樣推薦在項(xiàng)目中使用Dio庫。

Dio文檔地址: pub.dev地址:dio | Dart Package

一、項(xiàng)目目錄結(jié)構(gòu)

Flutter網(wǎng)絡(luò)請求Dio庫的使用及封裝方法

文件夾功能
components放置全局共用組件
router全局路由管理
service管理接口請求并對返回?cái)?shù)據(jù)進(jìn)行處理,復(fù)雜功能邏輯處理
storeprovider全局狀態(tài)管理
utile工具類,例如:接口請求工具類,數(shù)據(jù)持久化工具類,加密解密工具類……
views界面管理,實(shí)現(xiàn)界面UI繪制的代碼邏輯

二、封裝思路:

1、在DioRequest工具類中統(tǒng)一初始化網(wǎng)絡(luò)請求常見配置,實(shí)現(xiàn)請求攔截器、響應(yīng)攔截器以及錯誤處理。

2、統(tǒng)一在service中管理接口請求,并且對返回的數(shù)據(jù)根據(jù)實(shí)際需求進(jìn)行處理,如果數(shù)據(jù)的修改需要更新UI或者需要全局共享該數(shù)據(jù),可以結(jié)合provider實(shí)現(xiàn)。

三、添加依賴

在pubspec.yaml文件中添加所需要的第三方依賴庫

dev_dependencies:
  flutter_test:
    sdk: flutter 
  # The "flutter_lints" package below contains a set of recommended lints to
  # encourage good coding practices. The lint set provided by the package is
  # activated in the `analysis_options.yaml` file located at the root of your
  # package. See that file for information about deactivating specific lint
  # rules and activating additional ones.
  flutter_lints: ^1.0.0
  # 數(shù)據(jù)請求
  dio: ^4.0.4

四、簡單實(shí)現(xiàn)網(wǎng)絡(luò)請求

utils目錄中新建dio_request.dart文件實(shí)現(xiàn)DioRequest網(wǎng)絡(luò)請求的工具類。

import 'package:dio/dio.dart';
/// dio網(wǎng)絡(luò)請求配置表 自定義
class DioConfig {
  static const baseURL = 'http://117.34.71.31:8081/paas-admin'; //域名
  static const timeout = 10000; //超時時間
} 
// 網(wǎng)絡(luò)請求工具類
class DioRequest {
  late Dio dio;
  static DioRequest? _instance;
  /// 構(gòu)造函數(shù)
  DioRequest() {
    dio = Dio();
    dio.options = BaseOptions(
        baseUrl: DioConfig.baseURL,
        connectTimeout: DioConfig.timeout,
        sendTimeout: DioConfig.timeout,
        receiveTimeout: DioConfig.timeout,
        contentType: 'application/json; charset=utf-8',
        headers: {});
    /// 請求攔截器 and 響應(yīng)攔截機(jī) and 錯誤處理
    dio.interceptors.add(InterceptorsWrapper(onRequest: (options, handler) {
      print("\n================== 請求數(shù)據(jù) ==========================");
      print("url = ${options.uri.toString()}");
      print("headers = ${options.headers}");
      print("params = ${options.data}");
      return handler.next(options);
    }, onResponse: (response, handler) {
      print("\n================== 響應(yīng)數(shù)據(jù) ==========================");
      print("code = ${response.statusCode}");
      print("data = ${response.data}");
      print("\n");
      handler.next(response);
    }, onError: (DioError e, handler) {
      print("\n================== 錯誤響應(yīng)數(shù)據(jù) ======================");
      print("type = ${e.type}");
      print("message = ${e.message}");
      print("\n");
      return handler.next(e);
    }));
  }
  static DioRequest getInstance() {
    return _instance ??= DioRequest();
  }
}

五、實(shí)現(xiàn)登錄注冊服務(wù)

lib下新建service目錄,并在service目錄中新建login.dart文件。

import 'dart:convert';

import 'package:cyber_security/utils/http.dart';

class LoginService {
  /// 獲取用戶數(shù)據(jù)中心列表
  static Future<List> getDataCenter() async {
    var response = await DioRequest.getInstance().dio.get('/getDataCenter');
    var data = jsonDecode(response.toString());
    return data['dataCenterList'];
  }

  /// 登錄接口
  static login(value) async {
    var response = await DioRequest.getInstance()
        .dio
        .post('/sys/login', queryParameters: value);
    var data = jsonDecode(response.toString()); 
    /// 對返回的身份憑證全局持久化存儲
    return data['key'];
  }

  /// 獲取權(quán)限列表
  static menuNav() async {
    var response = await DioRequest.getInstance().dio.get('/sys/menu/nav');
    var data = jsonDecode(response.toString());
    return data['key'];
  }
}

六、使用service服務(wù)

@override
  void initState() {
    // TODO: implement initState
    super.initState();
    /// 請求用戶數(shù)據(jù)中心數(shù)據(jù)
    LoginService.getDataCenter().then((value) {
      setState(() {
        _dataCenterList = value;
      });
    });
  }

感謝各位的閱讀,以上就是“Flutter網(wǎng)絡(luò)請求Dio庫的使用及封裝方法”的內(nèi)容了,經(jīng)過本文的學(xué)習(xí)后,相信大家對Flutter網(wǎng)絡(luò)請求Dio庫的使用及封裝方法這一問題有了更深刻的體會,具體使用情況還需要大家實(shí)踐驗(yàn)證。這里是億速云,小編將為大家推送更多相關(guān)知識點(diǎn)的文章,歡迎關(guān)注!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI