Flutter Dio - مراجعة كاملة

Dio هو عميل HTTP لـ Flutter مع العديد من الميزات. كثير من الناس يحبونه بسبب بساطته وغناه بالميزات. اليوم ، سنتعلم كيفية استخدامه لتحسين تطوير تطبيقك في Flutter. هيا بنا نبدأ!




تثبيت

لنبدأ في كيفية تثبيت Dio. نظرًا لأن dio يعتمد على Dart بدون Flutter ، فلديك خياران لتثبيته:


مع Dart:

dart pub add dio

مع Flutter: 

flutter pub add dio

لكن هل تعلم أن Dio لديها العديد من الحزم المختلفة لحالات استخدام محددة؟ دعونا نستكشفها:

  • dio_cookie_manager - مدير ملفات تعريف الارتباط لـ Dio
  • dio_http2_adapter - Dio HttpClientAdapter الذي يدعم Http / 2.0
  • dio_smart_retry - مكتبة إعادة المحاولة المرنة لـ dio
  • http_certificate_pinning - تثبيت شهادة Https من أجل Flutter
  • curl_logger_dio_interceptor - Dio HTTP cache interceptor مع متاجر متعددة تحترم توجيهات HTTP (أو لا)
  • dio_http_cache - مكتبة ذاكرة تخزين مؤقت بسيطة لـ Dio مثل Rxcache في Android
  • pretty_dio_logger - Pretty Dio logger هو جهاز اعتراض Dio يسجل مكالمات الشبكة بتنسيق جميل وسهل القراءة.


لن نستخدم هذه في مقال اليوم. سنركز على أساسيات Dio لأن حزمة dio الرئيسية بها بالفعل العديد من الميزات.


الاستخدام الأساسي

لاستخدام Dio ، علينا أولاً إنشاء متغير يسمى Dio () class. هيا بنا نقوم بذلك:

import 'package:dio/dio.dart';
var dio = Dio;

يحتوي Dio () على تكوينات أساسية ، ولكن يمكنك تعيين خيارات مختلفة:

dio
..options.baseUrl = baseUrl
..options.connectTimeout = 50000
..options.receiveTimeout = 30000


طرق الطلب

يمكنك الحصول على رد باستخدام dio.get () ، ولكن هناك العديد من طرق الطلب الأخرى:

Future<Response> get(...)
Future<Response> post(...)
Future<Response> put(...)
Future<Response> delete(...)
Future<Response> head(...)
Future<Response> path(...)
Future<Response> download(...)
Future<Response> fetch(...)

لكن الآن قد تسأل نفسك ، ماذا أكتب بين قوسين؟

خيارات الطلب

إليك كل ما يمكنك تحديده بين قوسين:

{
/// Http method.
String method;

/// Request base url, it can contain sub path, like: 'https://www.google.com/api/'.
String baseUrl;

/// Http request headers.
Map<String, dynamic> headers;

/// Timeout in milliseconds for opening url.
int connectTimeout;

/// Whenever more than [receiveTimeout] (in milliseconds) passes between two events from response stream,
/// [Dio] will throw the [DioError] with [DioErrorType.RECEIVE_TIMEOUT].
/// Note: This is not the receiving time limitation.
int receiveTimeout;

/// Request data, can be any type.
T data;

/// If the `path` starts with 'http(s)', the `baseURL` will be ignored, otherwise,
/// it will be combined and then resolved with the baseUrl.
String path='';

/// The request Content-Type. The default value is 'application/json; charset=utf-8'.
/// If you want to encode request body with 'application/x-www-form-urlencoded',
/// you can set [Headers.formUrlEncodedContentType], and [Dio]
/// will automatically encode the request body.
String contentType;

/// [responseType] indicates the type of data that the server will respond with
/// options which defined in [ResponseType] are `JSON`, `STREAM`, `PLAIN`.
///
/// The default value is `JSON`, dio will parse response string to json object automatically
/// when the content-type of response is 'application/json'.
///
/// If you want to receive response data with binary bytes, for example,
/// downloading a image, use `STREAM`.
///
/// If you want to receive the response data with String, use `PLAIN`.
ResponseType responseType;

/// `validateStatus` defines whether the request is successful for a given
/// HTTP response status code. If `validateStatus` returns `true` ,
/// the request will be perceived as successful; otherwise, considered as failed.
ValidateStatus validateStatus;

/// Custom field that you can retrieve it later in [Interceptor][Transformer] and the [Response] object.
Map<String, dynamic> extra;
/// Common query parameters
Map<String, dynamic /*String|Iterable<String>*/ > queryParameters;
/// [collectionFormat] indicates the format of collection data in request
/// options which defined in [CollectionFormat] are `csv`, `ssv`, `tsv`, `pipes`, `multi`,`multiCompatible`.
/// The default value is `multiCompatible`
late CollectionFormat collectionFormat;

}


مخطط الاستجابة

لكن ما الذي ستحصل عليه كرد؟ حسنًا ، هذه القائمة ليست طويلة هذه المرة 

{
/// Response body. may have been transformed, please refer to [ResponseType].
T? data;
/// Response headers.
Headers headers;
/// The corresponding request info.
Options request;
/// Http status code.
int? statusCode;
String? statusMessage;
/// Whether redirect
bool? isRedirect;
/// redirect info
List<RedirectInfo> redirects ;
/// Returns the final real request uri (maybe redirect).
Uri realUri;
/// Custom field that you can retrieve it later in `then`.
Map<String, dynamic> extra;
}


المعترضون - Interceptors

يمكنك استدعاء وظائف مختلفة في حالات مختلفة من الطلب. يمكنك تنفيذ شيء ما قبل إرسال الطلب ، أو عندما تحصل على رد أو عندما تحصل على خطأ. دعنا نراه في العمل:

dio.interceptors.add(InterceptorsWrapper(
onRequest:(options, handler){
// Do something before request is sent
return handler.next(options); //continue
// If you want to resolve the request with some custom data,
// you can resolve a `Response` object eg: `handler.resolve(response)`.
// If you want to reject the request with a error message,
// you can reject a `DioError` object eg: `handler.reject(dioError)`
},
onResponse:(response,handler) {
// Do something with response data
return handler.next(response); // continue
// If you want to reject the request with a error message,
// you can reject a `DioError` object eg: `handler.reject(dioError)`
},
onError: (DioError e, handler) {
// Do something with response error
return handler.next(e);//continue
// If you want to resolve the request with some custom data,
// you can resolve a `Response` object eg: `handler.resolve(response)`.
}
));


معالجة الأخطاء

أخيرًا ، نريد أن نلقي نظرة على كيفية اكتشاف الأخطاء. نقوم بذلك باستخدام قالب بسيط للتجربة:

try {
//404
await dio.get('https://wendux.github.io/xsddddd');
} on DioError catch (e) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx and is also not 304.
if (e.response != null) {
print(e.response.data)
print(e.response.headers)
print(e.response.requestOptions)
} else {
// Something happened in setting up or sending the request that triggered an Error
print(e.requestOptions)
print(e.message)
}
}
//DioError scheme
{
/// Response info, it may be `null` if the request can't reach to
/// the http server, for example, occurring a dns error, network is not available.
Response? response;
/// Request info.
RequestOptions? request;
/// Error descriptions.
String message;

DioErrorType type;
/// The original error/exception object; It's usually not null when `type`
/// is DioErrorType.DEFAULT
dynamic? error;
}
//DioErrorType
enum DioErrorType {
/// It occurs when url is opened timeout.
connectTimeout,

/// It occurs when url is sent timeout.
sendTimeout,

///It occurs when receiving timeout.
receiveTimeout,

/// When the server response, but with a incorrect status, such as 404, 503...
response,

/// When the request is cancelled, dio will throw a error with this type.
cancel,

/// Default error type, Some other Error. In this case, you can
/// use the DioError.error if it is not null.
other,
}


مزيد من القراءة والاستنتاج

في هذه المقالة ، تعلمت أساسيات حل طلب HTTP "Dio". لقد رأيت مدى سهولة استخدامه ومدى قوته.

في المقالات القليلة التالية ، سأقدم حزمًا أكثر تعقيدًا إلى حد ما وأشرحها. إذا كنت لا تريد أن يفوتك هذا ، أنصحك بمتابعي. بذلت قصارى جهدي لكتابة أسهل برنامج تعليمي يفهمه الجميع. إذا كنت تقدر هذا العمل ، فسأكون ممتنًا جدًا إذا تمكنت من دعم هذا المحتوى عالي الجودة  


شكرا للقراءة ، أتمنى لك يوما سعيدا!

تعليقات