網(wǎng)站首頁(yè) 編程語(yǔ)言 正文
Dart語(yǔ)言內(nèi)置的HttpClient
實(shí)現(xiàn)了基本的網(wǎng)絡(luò)請(qǐng)求相關(guān)的操作。但HttpClient
本身功能較弱,很多網(wǎng)絡(luò)請(qǐng)求常用功能都不支持,因此在實(shí)際項(xiàng)目中,我們更多是使用dio庫(kù)實(shí)現(xiàn)網(wǎng)絡(luò)請(qǐng)求。
注:Flutter
官網(wǎng)同樣推薦在項(xiàng)目中使用Dio
庫(kù)。
Dio文檔地址: pub.dev地址:dio | Dart Package
一、項(xiàng)目目錄結(jié)構(gòu)
文件夾 | 功能 |
---|---|
components | 放置全局共用組件 |
router | 全局路由管理 |
service | 管理接口請(qǐng)求并對(duì)返回?cái)?shù)據(jù)進(jìn)行處理,復(fù)雜功能邏輯處理 |
store | provider全局狀態(tài)管理 |
utile | 工具類,例如:接口請(qǐng)求工具類,數(shù)據(jù)持久化工具類,加密解密工具類…… |
views | 界面管理,實(shí)現(xiàn)界面UI繪制的代碼邏輯 |
二、封裝思路:
1、在DioRequest
工具類中統(tǒng)一初始化網(wǎng)絡(luò)請(qǐng)求常見(jiàn)配置,實(shí)現(xiàn)請(qǐng)求攔截器、響應(yīng)攔截器以及錯(cuò)誤處理。
2、統(tǒng)一在service
中管理接口請(qǐng)求,并且對(duì)返回的數(shù)據(jù)根據(jù)實(shí)際需求進(jìn)行處理,如果數(shù)據(jù)的修改需要更新UI或者需要全局共享該數(shù)據(jù),可以結(jié)合provider
實(shí)現(xiàn)。
三、添加依賴
在pubspec.yaml文件中添加所需要的第三方依賴庫(kù)
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ù)請(qǐng)求 dio: ^4.0.4
四、簡(jiǎn)單實(shí)現(xiàn)網(wǎng)絡(luò)請(qǐng)求
在utils
目錄中新建dio_request.dart
文件實(shí)現(xiàn)DioRequest
網(wǎng)絡(luò)請(qǐng)求的工具類。
import 'package:dio/dio.dart'; /// dio網(wǎng)絡(luò)請(qǐng)求配置表 自定義 class DioConfig { static const baseURL = 'http://117.34.71.31:8081/paas-admin'; //域名 static const timeout = 10000; //超時(shí)時(shí)間 } // 網(wǎng)絡(luò)請(qǐng)求工具類 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: {}); /// 請(qǐng)求攔截器 and 響應(yīng)攔截機(jī) and 錯(cuò)誤處理 dio.interceptors.add(InterceptorsWrapper(onRequest: (options, handler) { print("\n================== 請(qǐng)求數(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================== 錯(cuò)誤響應(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)登錄注冊(cè)服務(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()); /// 對(duì)返回的身份憑證全局持久化存儲(chǔ) 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(); /// 請(qǐng)求用戶數(shù)據(jù)中心數(shù)據(jù) LoginService.getDataCenter().then((value) { setState(() { _dataCenterList = value; }); }); }
原文鏈接:https://blog.csdn.net/qq_16221009/article/details/124012070
相關(guān)推薦
- 2023-07-22 macos通過(guò)homebrew安裝多版本node
- 2022-09-10 Python自動(dòng)打印被調(diào)用函數(shù)變量名及對(duì)應(yīng)值?_python
- 2022-10-17 Go?WaitGroup及Cond底層實(shí)現(xiàn)原理_Golang
- 2022-05-29 C#使用DirectX.DirectSound播放語(yǔ)音_C#教程
- 2022-06-14 ASP.NET?Core?MVC在視圖中使用依賴注入_實(shí)用技巧
- 2022-05-12 寶塔面板配置SSL證書(shū)
- 2024-01-31 nginx配置文件中最后一個(gè) include servers/*;作用是什么?
- 2022-10-05 Win10下自帶的PowerShell讀取文件哈希值_PowerShell
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運(yùn)行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲(chǔ)小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運(yùn)算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過(guò)濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯(cuò)誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實(shí)現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡(jiǎn)單動(dòng)態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對(duì)象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊(duì)列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支