Flutter?Dio?簡單封裝demo
更新時間:2023年07月27日 10:39:36 作者:大蝦啊啊啊
這篇文章主要為大家介紹了Flutter Dio簡單封裝示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
Flutter Dio封裝
import 'package:dio/dio.dart'; import 'package:path_provider/path_provider.dart'; import 'package:znw/app/net/url_config.dart'; class HttpClient { late Dio dio; static HttpClient instance = HttpClient._internal(); ///工廠構造函數(shù)與普通構造函數(shù)的區(qū)別在于, ///工廠構造函數(shù)可以自定義實例的創(chuàng)建過程,并根據(jù)需要返回一個新的對象或現(xiàn)有的對象。 factory HttpClient() { return instance; } HttpClient._internal() { print('構造函數(shù)。。。。。。。。。。。。。。'); dio = Dio(); dio.options.baseUrl = UrlConfig.BASE_URL; dio.options.connectTimeout = 8000; dio.interceptors.add(LogInterceptor(responseBody: true)); // 輸出響應內容體 } /// get請求 Future<Response?> get(String url, {Map<String, dynamic>? map}) async { try { var result = await dio.get(url, queryParameters: map); return result; } catch (e) { print('HttManager get e $e }'); return null; } } ///post請求 Future<Response?> post(String url, Map<String, dynamic>? map) async { try { var result = await dio.post(url, queryParameters: map); return result; } catch (e) { print('HttManager post e $e }'); return null; } } ///上傳文件 fileName 文件名字 fileDir 文件路徑 formData 自定義參數(shù) Future<Response?> uploadFile(String url, String? fileName, String fileDir, Map<String, dynamic> formData) async { try { formData['file'] = await MultipartFile.fromFile(fileDir, filename: fileName); var response = await dio.post(url, data: formData); print(response.data); return response; } catch (e) { return null; } } ///下載文件 downLoadPath下載路徑, ///fileName 下載之后生成的文件名字, ///onProgress 下載進度 ///onFinish 下載完成 downLoad( String downLoadPath, String fileName, Function(int count, int total) onProgress, Function(String path) onFinish, Function(DioError e) onError) async { final directory = await getExternalStorageDirectory(); String localPath = directory!.path; String savePath = "$localPath/$fileName"; String apkUrl = downLoadPath; ///參數(shù)一 文件的網(wǎng)絡儲存URL ///參數(shù)二 下載的本地目錄文件 ///參數(shù)三 下載監(jiān)聽 try { await dio.download(apkUrl, savePath, onReceiveProgress: (received, total) { if (total != -1) { ///當前下載的百分比例 print("${(received / total * 100).toStringAsFixed(0)}%"); onProgress(received, total); } }); onFinish(savePath); print(savePath); } on DioError catch (e) { // 異常處理代碼 onError(e); } } }
代碼解釋都在注釋里啦~
以上就是Flutter Dio 簡單封裝demo的詳細內容,更多關于Flutter Dio封裝的資料請關注腳本之家其它相關文章!
相關文章
解析Android開發(fā)優(yōu)化之:軟引用與弱引用的應用
Java從JDK1.2版本開始,就把對象的引用分為四種級別,從而使程序能更加靈活的控制對象的生命周期。這四種級別由高到低依次為:強引用、軟引用、弱引用和虛引用,本篇文章重點介紹一下軟引用和弱引用2013-05-05Android WebView或手機瀏覽器打開連接問題解決辦法總結
這篇文章主要介紹了Android WebView或手機瀏覽器打開連接問題解決辦法總結的相關資料,需要的朋友可以參考下2017-03-03詳解Android?Flutter中SliverAppBar的使用教程
對于一個APP來說,肯定會有一個AppBar,這個AppBar一般包含了APP的導航信息等。在lutter已經(jīng)為我們提供了一個非常強大的AppBar組件,這個組件叫做SliverAppBar。本文就來聊聊它的具體使用吧2023-01-01