Changelog¶
2.0.0¶
A major release: it raises the minimum Dart and Flutter versions and adds new exception types (see the breaking changes below). It brings streaming, path parameters, custom error objects, a finer-grained set of connection errors, and many fixes to error handling. There is also a new documentation site.
Breaking changes¶
- Minimum versions:
playx_core ^2.0.0requires Dart>=3.12.0and Flutter>=3.44.0, so these are now the minimum versions ofplayx_networktoo. - New exception types:
NetworkExceptionis a sealed class, so an exhaustiveswitchover it must handle the new subclassesServerUnreachableException,CorsException,SecureConnectionExceptionandReceiveTimeoutException(or keep a catch-all case). - Slow responses: Dio's
receiveTimeoutis now aReceiveTimeoutExceptioninstead of aSendTimeoutException. Code that caughtSendTimeoutExceptionfor slow responses should also catchReceiveTimeoutException.
New features¶
Streaming and SSE¶
getStreamandpostStreamconsume streaming endpoints (SSE, NDJSON, chunked text and binary) through the new sealedNetworkStreamResult, which haswhen,map,mapAsync,mapStream,mapStreamAsyncandtoList().getSseandpostSseare conveniences for Server-Sent Events, with thePlayxSseEventmodel. They sendAccept: text/event-stream.PlayxStreamFormatselects how bytes are decoded:bytes,text,json(one JSON document per line, NDJSON) orsse.- Decoding uses a streaming UTF-8 decoder, so multibyte characters split across chunks are reassembled. The SSE parser follows the specification: CR, LF and CRLF line endings, a leading BOM, a persistent last event id, and no events from partial lines or data-less blocks.
- The stream follows its listener: pause and resume are honoured, and cancelling the subscription, cancelling the token, or a source error aborts the HTTP request. A stream always completes after a terminal error. Error response bodies are read (up to 64 KB) so the error mapper receives the server's message.
toList()returns aNetworkResult.errorif the stream errors. It never completes for endless streams.- Streams support path parameters, and merge
options.headersinstead of replacing them. The idle receive timeout is disabled unlessoptions.receiveTimeoutis set.
Path parameters¶
pathParameterssubstitutes{placeholder}segments in the path of every request (for example'users/{userId}'with{'userId': 42}). Values are URL-encoded.customPathParametersonPlayxNetworkClient(andattachCustomPathParametersper request) supplies app-wide values, likecustomQuerydoes for query parameters.
Custom error objects¶
errorExtraMapper(client-level and per request) maps an error response to your own object, exposed asApiException.extra. Read it withresult.errorExtraAs<E>()orexception.extraAs<E>(), no cast needed.ErrorMapperis unchanged.
Empty responses¶
treatEmptyResponseAsSuccess(defaultfalse) returnsNetworkResult.success([])for list requests that succeed with an empty body or an empty list, instead of anEmptyResponseException.fromJsonis optional ondelete. Without it any successful response isNetworkResult.success(null)(usedelete<void>), and with it an empty body is a success and the mapper receivesnull.- Documented that
204 No ContentneedssuccessRequestCodes: [200, 201, 204]. The default is unchanged.
Connection failures¶
ServerUnreachableException(connection refused, reset, closed or timed out, no route to host) and, on the web,CorsException, so not every failed connection is reported asNoInternetConnectionException. The exception is chosen from the OS error. A failure that can't be identified staysNoInternetConnectionException.- The optional
hasInternetConnectioncallback onPlayxNetworkClient(for example backed byconnectivity_plus) tells offline from unreachable reliably. It is only called after a connection failure. SecureConnectionExceptionfor rejected certificates and failed TLS handshakes (Dio reports a handshake failure asunknownorconnectionError). The connectivity callback is not called for them.- New
ExceptionMessagegettersserverUnreachable,corsError,secureConnectionErrorandreceiveTimeout. They have defaults (defaultError, andsendTimeoutforreceiveTimeout), so existing subclasses keep compiling. English and Arabic provide their own.
Changes¶
- A response body that cannot be parsed (for example invalid JSON) is reported as
InvalidFormatException. It was anUnexpectedErrorException, and theInvalidFormatExceptionbranch could never be reached. - Dio's
transformTimeout(parsing took too long) is anUnableToProcessException. - Requests made with a Dio that keeps the default
validateStatusare handled consistently: error responses of stream requests keep the API message andextradata, and a status listed insuccessRequestCodesthat Dio rejects (for example304) is a success for every request type.
Bug fixes¶
- Cancellation: cancelling a request exactly while its response was being mapped could throw an uncaught
Bad state: Future already completed. The race is handled and the request returns aRequestCanceledException. Downloads also no longer let non-Exceptionerrors (such as aStateError) escape. - Default error parsing:
DefaultApiErrorreads Strapi'smessage: [{messages: [...]}](that branch could never run), joins list messages such asmessage: ["a", "b"], supports{"error": "..."}, and reads each field on its own so a wrongly typedstatusCodeno longer discards the message. Blank messages are treated as missing. - Per-request settings: custom
exceptionMessages,shouldShowApiErrorsandunauthorizedRequestCodespassed in a request'ssettingsnow apply to error status codes of every request type, including errors Dio throws asbadResponse. Only the client-level settings were used before. - Copying a
Diofor per-request log settings no longer duplicates Dio's default interceptor. - Fixed the non-exhaustive switch over
DioExceptionTypeby handlingtransformTimeout, introduced in Dio 5.10.
Dependencies¶
playx_core ^2.0.0,dio ^5.11.1.- Widened ranges so apps can pick their versions:
sentry_dio >=9.16.0 <11.0.0,talkerandtalker_dio_logger>=5.1.16 <6.0.0,dio_web_adapter >=2.1.2 <3.0.0.sentry_diois only re-exported; apps that move tosentry_dio10 should read its migration notes (AndroidminSdk26, Swift Package Manager on Apple platforms, span streaming on by default). package:webis now a direct dependency.
1.0.0¶
- Nested JSON Key Extraction: Added
dataKeyparameter to all network requests to extract nested JSON values before parsing. - Item-Level Nested Key Extraction: Added
itemDataKeyto all list-returning requests (getList,postList, etc.) to unwrap each list item (e.g.,itemDataKey: 'attributes') before passing it to the mapper. - Smart Request Cancellation Manager: Added
cancelTagparameter to manage and cancel multiple requests at once with automaticcancelOldsupport. - Mapping Cancellation: Better support for canceling requests during JSON mapping in isolates. Now, when a request is canceled, the mapping process is also canceled to save resources and improve performance.
0.6.0¶
- Updated dependencies to their latest versions.
- PATCH Request Support: Added new methods (patch and patchList) to easily perform PATCH API requests.
- Per-Request Error Mapping: You can now pass a custom ErrorMapper to individual API calls for more specific error handling.
- Granular Logging Control: Added new settings to control exactly what gets printed in the logs (e.g., toggle response data, request headers, etc.).
- Added dio_smart_retry package to support retrying failed requests with exponential backoff.
0.5.1¶
- Updated dependencies to their latest versions.
- Enhanced logging errors and exceptions to provide more detailed information.
0.5.0¶
Note: This version contains breaking changes.
New Features¶
- Export
DioClient: A simple and customizable HTTP client based on Dio is now available directly from theplayx_networkpackage.
Improvements¶
Logger Overhaul¶
- Replaced
pretty_dio_loggerwithtalker_dio_loggerfor better log control and Talker integration. - Updated
PlayxNetworkLoggerSettingsto support detailed logging configuration. - Integrated
PlayxLoggerfor consistent logging across the Playx ecosystem.
Other¶
- Updated dependencies to their latest versions.
- Bump minimum Dart SDK version to 3.5.0 and Flutter SDK version to 3.24.0.
- Migrated Android example project to Kotlin DSL.
0.4.0¶
Note: This version contains breaking changes.
Breaking Changes¶
- NetworkResult
now includes data and error fields for easier access instead of networkDataandnetworkErrorgetters. - Renamed FormatException → InvalidFormatException to avoid conflict with Dart’s built-in FormatException.
New Features && Enhancements¶
- Update dio to v5.8.0+1
- Support FileAccessMode in Dio.download to change download file opening mode.
NetworkResult¶
- New
mapDataAsyncOrNullMethod which maps the success data to another type asynchronously, With option to map the error case or return null. whenmethod now returns the value instead of void.
NetworkException¶
- NetworkException now extends Exception for better error handling.
- All exception classes now follow a streamlined format with default values for status codes.
0.3.1 - 0.3.2¶
- fix: bug when initializing PlayxNetworkClient.
0.3.0¶
- Mapping Enhancements:
- Enhanced mapping of Dio responses with support for processing in an isolate using the
work_managerpackage or thecomputemethod. - Added parameters for mapping options in
PlayxNetworkClientSettings:useIsolateForMappingJson: Determines whether to use an isolate for mapping JSON responses.useWorkManagerForMappingJsonInIsolate: Specifies whether to usework_manageror thecomputefunction for JSON mapping in an isolate.
-
Added the ability to override
PlayxNetworkClientSettingsfor individual requests, similar to overridinglogSettingsorexceptionMessages. -
NetworkResult Enhancements:
-
Added the following convenience getters to the
NetworkResultclass:isSuccess: Checks if the network call is successful.isError: Checks if the network call has failed.networkData: Returns the data if the call is successful, otherwise returnsnull.networkError: Returns the error if the call has failed.
-
Asynchronous Mapping:
- Introduced new mapping methods for
NetworkResult:mapDataAsync: Maps a network response (success or error) to a desired model asynchronously.mapDataAsyncInIsolate: Maps a network response asynchronously in an isolate, with configurable options:mapper: The function for transforming data.exceptionMessage: A message to display in case of exceptions.useWorkManager: Determines whether to usework_managerorcomputefor JSON mapping.mapAsyncInIsolate: Separately maps success and error cases asynchronously in an isolate, with configurable options:success: The function for mapping successful responses.error: The function for mapping error responses.useWorkManager: Determines whether to usework_managerorcompute.
0.2.3¶
- fix: Bug causing error not being reported successfully.
- feat: Update
sentry_diopackage to v8.11.0.
0.2.2¶
- Add ability to download content using dio
downloadmethod.
0.2.0 - 0.2.1¶
Note: This version contains breaking changes.
Breaking Changes¶
- Combined
PlayxNetworkClientSettings: - Merged settings for
PlayxNetworkClientinto a newPlayxNetworkClientSettingsclass. - Renamed
LoggerSettingstoPlayxNetworkLoggerSettings.
New Features¶
- Custom Queries Support:
- Added the ability to include custom queries in network requests, enhancing flexibility for API interactions.
- Users can decide whether to use custom queries on a per-request basis by using the
attachCustomQueryoption.
Improvements¶
- Enhanced
PlayxNetworkLoggerSettings: -
Added options for attaching a logger in debug and release modes (
attachLoggerOnDebugandattachLoggerOnRelease). -
Updated Dio Package:
- Upgraded Dio package to v5.7.0 for improved performance and features.
0.1.2¶
New Features¶
- Isolate-Based Data Processing:
- Integrated Dart's
Isolateto handle data processing in network responses, offloading CPU-intensive tasks to separate threads, which improves app performance, particularly in scenarios involving large datasets. - Sentry Dio Integration:
- Added the Sentry Dio package to automatically capture and report errors in network requests to Sentry. This integration provides better monitoring and error tracking for network-related issues.
Improvements¶
- Updated
JsonMapperSignature: - The
JsonMapper<T>signature has been updated fromT Function(dynamic json)toFutureOr<T> Function(dynamic json)to support both synchronous and asynchronous JSON processing. This allows for more flexible and efficient handling of JSON data.
Bug Fixes¶
- Fixed an issue where
getListandpostListmethods did not return results when the API response was not a list. Now, proper error handling ensures that non-list responses are processed correctly, preventing potential runtime errors.
0.1.1¶
- Update packages.
0.1.0¶
Note: This version contains breaking changes.
- Update packages.
- Update
onUnauthorizedRequestReceivedcallback to takeResponseinstead ofvoidto be able to customize unauthorized error handling based on response. - Add
namefield for default error model.
0.0.9¶
- Update packages.
- Add unauthorizedRequestCodes to be able to handle different unauthorized request status codes returned from the api and fire onUnauthorizedRequestReceived callback.
- Add successRequestCodes to be able to handle different success request status codes returned from the api and fire onUnauthorizedRequestReceived callback.
- Enhance printing non api error messages.
0.0.8¶
- Update packages.
- Add
statusCodetoApiExceptionto be able to handle different error status codes returned from the api.
0.0.7¶
- Update packages.
- Bug fix, causing
onUnauthorizedRequestReceivednot called when receiving unauthorized request on certain cases.
0.0.6¶
- Add ability to not handle unauthorized requests on each request.
- [Breaking Change]! : Each Network Exception now takes errorMessage of type String instead of exceptionMessage
0.0.5¶
- Enhancements for default error model.
0.0.4¶
- Make
customHeadersto be of type function that return a map to be updated correctly.
0.0.3¶
- fix some bugs causing error not being reported successfully.
0.0.2¶
- update from json to take dynamic json instead of map.
0.0.1¶
- initial release