Flutter之GetX之GetConnect

1|0Flutter之GetX之GetConnect

GetConnect可以便捷的通过http或websockets进行前后台通信。

1|1默认配置

能轻松的通过extend GetConnect就能使用GET/POST/PUT/DELETE/SOCKET方法与Rest API或websockets通信。

class UserProvider extends GetConnect { // Get request Future<Response> getUser(int id) => get('http://youapi/users/$id'); // Post request Future<Response> postUser(Map data) => post('http://youapi/users', body: data); // Post request with File Future<Response<CasesModel>> postCases(List<int> image) { final form = FormData({ 'file': MultipartFile(image, filename: 'avatar.png'), 'otherFile': MultipartFile(image, filename: 'cover.png'), }); return post('http://youapi/users/upload', form); } GetSocket userMessages() { return socket('https://yourapi/users/socket'); } }

1|2自定义配置

GetConnect具有多种自定义配置。可以配置base Url,配置响应,配置请求,添加权限验证,甚至是尝试认证的次数,除此之外,还可以定义一个标准的解码器,该解码器将把所有请求转换为模型,而不需要任何额外的配置。

class HomeProvider extends GetConnect { @override void onInit() { // All request will pass to jsonEncode so CasesModel.fromJson() httpClient.defaultDecoder = CasesModel.fromJson; httpClient.baseUrl = 'https://api.covid19api.com'; // baseUrl = 'https://api.covid19api.com'; // It define baseUrl to // Http and websockets if used with no [httpClient] instance // It's will attach 'apikey' property on header from all requests httpClient.addRequestModifier((request) { request.headers['apikey'] = '12345678'; return request; }); // Even if the server sends data from the country "Brazil", // it will never be displayed to users, because you remove // that data from the response, even before the response is delivered httpClient.addResponseModifier<CasesModel>((request, response) { CasesModel model = response.body; if (model.countries.contains('Brazil')) { model.countries.remove('Brazilll'); } }); httpClient.addAuthenticator((request) async { final response = await get("http://yourapi/token"); final token = response.body['token']; // Set the header request.headers['Authorization'] = "$token"; return request; }); //Autenticator will be called 3 times if HttpStatus is //HttpStatus.unauthorized httpClient.maxAuthRetries = 3; } @override Future<Response<CasesModel>> getCases(String path) => get(path); }

__EOF__

本文作者R1cardo
本文链接https://www.cnblogs.com/r1cardo/p/17289367.html
关于博主:评论和私信会在第一时间回复。或者直接私信我。
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角推荐一下。您的鼓励是博主的最大动力!
posted @   R1cardo  阅读(1422)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示