playx_core 2.0.0
playx_core: ^2.0.0 copied to clipboard
Core package for playx eco system contains shared classes and utilities.
Changelog #
2.0.0 #
Upgrading from 1.x? Follow the migration guide. The package now has full documentation in
doc/.
Breaking changes #
- Minimum SDK is now Dart
>=3.12.0 <4.0.0and Flutter>=3.44.0(was Dart 3.5 / Flutter 3.24), required bysimple_secure_storage0.4.3. PlayxEnvgetters are synchronous. Values are in memory afterload(), soawait PlayxEnv.getString(...)becomesPlayxEnv.getString(...).PlayxEnv.loadtakes aPlayxEnvSettingsinstead of named arguments, andPlayxEnv.instance(flutter_dotenv's globaldotenv) is removed in favor ofPlayxEnv.allandPlayxEnv.values.PlayxEnvmoved tolib/src/env/.- Stricter parsing in
PlayxEnvandPlayxSecurePrefs. Both use thesafe_converthelpers: an unrecognized bool (anything buttrue/false/1/0) reads asnull, sogetBoolreturns its fallback instead offalse;"1.5"reads as1for ints. PlayxSecurePrefsSettingsgroups theflutter_secure_storageoptions (iosOptions,androidOptions,linuxOptions,windowsOptions,macOsOptions) intoflutterSecureStorageOptions: PlayxFlutterSecureStorageOptions(...).webOptionsis removed.- The default
AndroidOptionsno longer setsencryptedSharedPreferences, whichflutter_secure_storage11 removed (existing Android data is migrated automatically on first access). - Web:
PlayxSecurePrefsnow uses AES-GCM encrypted preferences with a non-extractable WebCrypto key kept in IndexedDB for every storage type exceptmemory. No password, salt or key ships with the app. Data saved by 1.x withflutter_secure_storageis migrated automatically on the first start. WebUtils.setAppTitletakes named arguments on the web too (setAppTitle(title: 'x')), matching the non-web version. The two signatures differed, so the same call could not compile on both.
Added #
Secure preferences (see Secure preferences)
- Choice of backends via
PlayxSecurePrefsSettings.storageType(PlayxSecureStorageType). The default staysflutterSecureStorage:simpleSecureStorage: usessimple_secure_storage, configured withPlayxSimpleSecureStorageOptions.encryptedPrefs: stores AES-GCM encrypted values inSharedPreferencesAsync, configured withPlayxEncryptedPrefsOptions. The key is kept in the first healthy store ofkeyStores(simple_secure_storage, thenflutter_secure_storage) and is not replaced while values encrypted with it may still be readable. A per-device fallback key is used when no key store is available. Falls back tomemoryif preferences are unavailable.clear()only removes keys with the configured prefix.auto: uses the first backend ofautoOrder(default:simple_secure_storage,flutter_secure_storage,encryptedPrefs) that passes a health check, thenmemory. Values written, removed or cleared on a fallback backend are applied to the preferred backend once it works again.memory: in-memory only.
PlayxSecurePrefsSettings.encryptKeys(defaultfalse) hides key names where storage would expose them: encrypted prefs (all platforms, including web) andflutter_secure_storageon Android. Each value is stored under an HMAC-SHA256 of its name, keyed by a key kept in secure storage, and the name is kept inside the encrypted value. Existing values are converted when it is turned on or off. Theautojournal is encrypted as well.PlayxSecurePrefsSettings.throwOnError(defaulttrue). Whenfalse, storage errors are logged instead of thrown, andmemoryis used if the backend can't be created.PlayxSecurePrefs.migrateFromFlutterSecureStorage()moves existing data when switching an app away from the default backend.PlayxSecurePrefs.storageType,PlayxSecurePrefs.isInitializedandPlayxSecurePrefs.dispose().PlayxCore.dispose()now also disposesPlayxSecurePrefs.
Environment configuration (see Environment configuration)
- Layered configuration:
.env, then.env.<environment>(fromenvironment,--dart-define=PLAYX_ENV=<name>or the Flutter flavor), thenadditionalFiles, secure env,mergeWith,PLAYX_DEFINESanddartDefines. Later files can reference earlier values. --dart-definevalues without declaring them in code:--dart-define=PLAYX_DEFINES="DEBUG=true;API_URL=..."(orbase64:encoded.envcontent) is read automatically. Disable withusePlayxDefines: false.dartDefinescovers individual--dart-define/--dart-define-from-filevalues.requiredKeys, failing at startup with aPlayxEnvExceptionlisting missing keys. Missing files are logged, or throw whenisOptionalisfalse.- New getters:
getNum,getUri,getEnum,getDuration,getList(comma-separated or JSON),getMapandgetObject, each with amaybeGet*variant. EnvValues: an immutable set of values with all the typed getters, exposed asPlayxEnv.valuesand usable on its own (for example for remote config).isLoaded,environment,loadedFiles,all,containsKeyandisSecure, plusloadFromString,setMockValuesanddispose()for tests.PlayxCore.dispose()now also disposesPlayxEnv.
Secure env (see Secure env)
- Put sensitive values in a gitignored
.env.secrets(or CI variables) and rundart run playx_core:secure_env(dart run playx:secure_envin apps usingplayx) to generate an encrypted Dart file, passed asPlayxEnvSettings.secureEnv. Names and values are encrypted with AES-256-GCM and the key is embedded split, or passed with--dart-define=PLAYX_ENV_KEY. - Supports per-environment files,
--from-env,--from-env-prefix PLAYX_SECRET_and--definefor CI, and an encryptedPLAYX_SECURE_DEFINESdefine. Secure values are excluded fromPlayxEnv.all. - Sample Codemagic, GitHub Actions and Vercel configurations in
doc/ci/. Generated files start with// dart format offso the byte lists stay compact.
Preferences
- JSON helpers on
PlayxPrefs,PlayxAsyncPrefs,PlayxPrefsWithCacheandPlayxSecurePrefsto store maps, lists and objects:setMap/maybeGetMap/getMap,setList/maybeGetList/getList(with optionaltoJson/fromJsonitem converters) andsetObject/maybeGetObject/getObject. Invalid or mismatched stored values returnnullor the fallback.
Extensions and utilities (see Extensions and Utilities)
- Padding:
PlayxNumPaddingExtensionsonnum(p,px,py,pAll,pLR,pTB,pZero, single-sidept,pb,pl,pr, and RTL-awareps/peasEdgeInsetsDirectional) andPlayxWidgetPaddingExtensionsonWidget(withPadding,pAll,pSymmetric,pOnly,pDirectional,pZero), returningPadding. Values are unscaled; scale the number first (16.r.p) when using a scaling package. - Border extensions (
border_extensions.dart):radius,ellipticalRadius,borderRadiuswithTop/Bottom/Left/Rightand RTL-awareStart/Endvariants,roundedShape,borderandborderSideonnum;border/borderSideonColor;clipRounded,clipBorderRadiusandborderedon widgets. String.capitalizedInitialChar(Unicode-safe initial) andString.toPrettyJson().BuildContext.crossAxisCount(...)for responsive grid columns.ColorUtils(fromHex,fromRGB) is now exported fromplayx_core.dart.toLocalDateTime*andasLocalDateTime*accept autcOffsetto read timestamps without zone information in a given zone (for example a server sending local Saudi time).- Optional
onErrorcallback (MapOnError<T, S>) onMapUtils.mapAsync,MapUtils.mapAsyncInIsolateand theMapAsync<T>extension methods. When provided, errors thrown while running the mapper (or while dispatching the isolate task) are caught, logged (subject toprintError), and the value returned byonErroris returned instead of rethrowing. IfonErrorisnull(the default), errors are rethrown after logging.
Logging (see Logging)
PlayxCore.bootCore(loggerSettings:)configures thePLAYX CORElogger: turn colors off (no more^[[38;5;4min consoles that don't render ANSI), add the time, hide the boot messages withlevel: LogLevel.warning, or send logs elsewhere.PlayxLoggerSettings.printLoggerNameandprintDateTimenow work (they were accepted but ignored). New options:dateTimeFormat(PlayxLogDateTimeFormat),dateTimeFormatter,printLevel([INFO]-style labels) andtarget(PlayxLogTarget:debugPrint,stdoutordeveloperLog) to choose the output channel, for example to avoid theflutter:prefix that the platform adds toprintanddebugPrint. Messages are written as[time] [LEVEL] [name] [tag] message.- Colors are dropped automatically when the console can't show them (web,
NO_COLOR,TERM=dumb, astdoutterminal without ANSI support).--dart-define=PLAYX_LOG_COLORS=true|falseforces them on or off for a build, for example in an Android Studio run configuration, whose Run panel prints ANSI codes as text. PlayxLogTarget.developerLognow passes the logger name, the level anderror/stackTracetodart:developer'slog(styled by Android Studio and DevTools) instead of formatted text.DefaultColoredLoggerFormatter(plain single lines) has aconstconstructor.LogLevel,AnsiPen,LoggerFormatter,LoggerFilter,LoggerOutput,LogDetails,ExtendedLoggerFormatter,ColoredLoggerFormatterandTalkerLoggerSettingsare re-exported, so apps don't need a directtalker_loggerdependency.
Documentation
- Guides for every area in
doc/: getting started, preferences, secure preferences, environment configuration, secure env, extensions, utilities, logging, testing and a migration guide. The guides are published as a searchable website (with the API reference) on GitHub Pages by.github/workflows/docs.yml. The README is now a concise overview that links to them, and the example app demonstrates environments and secure env.
Changed #
- Dependencies:
flutter_secure_storage^11.2.0,simple_secure_storage^0.4.3,flutter_dotenv^6.0.1,pointycastle,flutter_lints^6.0.0 andlints^6.0.0. Ranges were widened forshared_preferences(>=2.3.0 <3.0.0),get_it(>=8.0.0 <10.0.0),equatable(>=2.0.7 <4.0.0),talker_logger,worker_managerandweb. clearOnReinstallno longer requiresPlayxPrefsto be created. It keeps using the same flag, so existing installs are not cleared.WebUtilsnow uses the web implementation on WebAssembly builds too (the condition isdart.library.js_interopinstead ofdart.library.html).- Secure preferences, environment and JSON helper code was reorganized into focused files and folders. Import
package:playx_core/playx_core.dartrather than files undersrc/.
Fixed #
BuildContext.formthrew outside aForminstead of returningnull(it now usesForm.maybeOf).asListIntandasListIntOrrejected values thatasListIntOrNullaccepts, such as[1, '2', 3.0]; they now convert the same way.PlayxAsyncPrefs.maybeGetString,maybeGetInt,maybeGetDoubleandmaybeGetBooldid not catch asynchronous errors; they now returnnullas documented.- A clean-up of the private
_mapAsyncisolate entry point (removed a redundanttry/catchthat only rethrew). - Documented that
context.sizeresolves toBuildContext's own render size rather than theMediaQuerysize; usecontext.width,context.heightorcontext.aspectRatiofor the screen size. PlayxLogger's documentation example used aPlayxLoggerSettings(name: ...)argument that doesn't exist.
Tests #
- Test coverage rose from about 80% to about 98%: loggers, all preference stores,
PlayxCore, secure storage backends and edge cases, env, secure env and its command, extensions, conversion helpers and web behavior (including browser tests).
1.0.0 #
- Added support for nested JSON keys using dot notation (e.g.,
'data.user.name') in allsafe_json_convertfunctions. - Introduced
toEnum/asEnumandtoUri/asUrisafe conversion functions. - Improved generic list parsing in
toListOrNullby adding a fallback toList<T>.from(value)for safer runtime casting. - Optimized
TalkerPlayxLoggerto strictly respect theenabledconfiguration, utilizedebugPrint, and automatically disable colored output in Web environments to avoid unformatted ANSI codes. - Refactored
PlayxColorExtensionsto eliminate deprecateddart:uigetters, transitioning to Flutter 3.24 wide-gamut compatibility (a,r,g,b). AddedfromHex,lighten,darken, andisDarkhelper methods. - Expanded core extension libraries (
String,Iterable,DateTime,Duration,bool,BuildContext) to include new highly-requested utilities:- String: Added helpers like
toIntOrNull(),isNumeric,isValidEmail,toSlug(), andNullableStringExtensionsonString?(e.g.,isNullOrEmpty). - Iterable: Added functional utilities
chunked,groupBy,sortedBy, and numeric aggregates (sum,average). - DateTime: Added boundary generators like
startOfDay,endOfMonth, andstartOfWeek. - Context: Mapped the complete Material 3
ColorSchemeproperties (e.g.,onPrimary,surfaceContainer) directly toBuildContextfor agile theming.
- String: Added helpers like
0.7.4 #
- Update packages
- Add new asTOr and asT safe json convert functions.
1.0.0-beta.4 1.0.0-beta.5 #
- Added v0.7.0 changes.
1.0.0-beta.3 #
- Add new
printErrorparam to**MapUtils** mapAsyncandmapAsyncInIsolatemethods to determine whether to print errors or not. - Update
asyncMapInIsolateinNestedIterablesExtensionsto include aprintErrorparameter andprintEachItemErrorparameter to determine whether to print errors for each item or not.
0.7.2-0.7.3 #
- Enhance logging methods in
PlayxCoreto use the newPlayxLoggersystem.
1.0.0-beta.2 #
Note: This release has breaking changes.
- Update flutter_secure_storage: to v10.0.0-beta.4.
- Added v0.6.0 changes.
1.0.0-beta.1 #
-
Add support for wasm support for web.
-
Update flutter_secure_storage: to v10.0.0-beta.2 which includes some breaking changes.
-
Updated dependencies.
-
Added
isWasmtoPlayxPlatformto detect if the app is running in a WebAssembly environment. -
Introduced
WebUtils, a new utility class providing common browser-side features for web apps:- Update the browser URL and query parameters without navigation.
- Control fullscreen mode (enter, exit, toggle).
- Set the browser tab title and application switcher label.
- Change
<body>background color directly or by CSS class. - Open links in new tabs.
- Reload the page.
0.7.0 #
Note: This release has breaking changes.
✨ Features #
-
New System Utilities (
common_utils.dart)setNavigationBarColor: Set navigation bar color and icon brightness.setOrientation: Lock screen orientation with optional rotation.hideKeyboard/showKeyboard: Control keyboard visibility.enterFullScreen/exitFullScreen: Toggle immersive full-screen mode.copyToClipboard/getClipboardText/clearClipboard: Manage clipboard content.setStatusBarColornow setsstatusBarBrightnessfor improved iOS support.
🧠 Type Conversion Enhancements #
-
Safe Conversion Utilities (
safe_convert.dart&safe_json_convert.dart)-
Added:
toNumOrNull,toNumOr,toNumtoDateTimeOrNull,toDateTimeOr,toDateTimetoLocalDateTimeOrNull,toLocalDateTimeOr,toLocalDateTime
-
Improved:
- List conversion with optional
fromJson - Renamed generic list conversion functions for consistency:
- toListOrNullT → toListOrNull
- toListTOr → toListOr
- oListT → toList
- Map conversion support for generic types (
<T, S>) asTOrNull: Now cleaner and more robust
- List conversion with optional
-
Refactored for consistency, better error handling, and improved documentation.
-
🚀 **New Logging System ** 🔥 #
This version introduces a modern, powerful, and highly configurable logging system using the talker_logger package.
✅ What's New
- 🔄 Replaced old
PlayxLoggerwith a modular and extensible system.
🧱 Core Components
PlayxBaseLogger: Abstract base for all logger implementations.TalkerPlayxLogger: Concrete logger usingtalker_logger, supports customization (name, colors, log levels, filters, formatters).PlayxLoggerSettings: Configure behavior globally (log level, console output, filters, etc.).PlayxLogger: Static utility class to manage and use named logger instances.
🔧 Integration Highlights
-
PlayxCorenow initializes a default logger named'PLAYX CORE'on setup. -
Internal operations like preference booting, environment loading, and error tracking now leverage the enhanced logger:
PlayxLogger.d('Debug message'); PlayxCore.logger.error('An error occurred', error:error); -
Existing utilities (
MapperUtilities,IterableExtensions) now use the new logger for standardized logging.
🧩 Dependency
- Added:
talker_logger: ^4.7.7topubspec.yaml.
0.6.2 0.6.3 #
- Update packages.
- Updates minimum supported SDK version to Flutter 3.24/Dart 3.5.
0.6.1 #
- Add new
printErrorparam to**MapUtils** mapAsyncandmapAsyncInIsolatemethods to determine whether to print errors or not. - Update
asyncMapInIsolateinNestedIterablesExtensionsto include aprintErrorparameter andprintEachItemErrorparameter to determine whether to print errors for each item or not.
0.6.0 #
Note: This release has breaking changes.
Breaking Changes
- MapUtils
mapAsyncandmapAsyncInIsolatenow require the following parameters:T data: The data to be mapped.Mapper<T, S> mapper: A required named parameter for the transformation logic.
- Extensions on
Iterable<T>- Updated
asyncMapandasyncMapInIsolateto requireMapper<T, S> mapperas a named parameter. NestedIterablesExtensions<T>:- Deprecated
asyncFlatMap. UseflatMapAsyncinstead. - Updated
flatMapandflatMapAsyncto requireMapper<T, S> mapperas a named parameter.
- Deprecated
- Updated
New Features
- MapUtils
- Enhanced
mapAsyncInIsolateto map items in an isolate usingworkerManagerby default. - Added a new
useWorkManagerparameter:- If
true, usesworkerManagerto execute tasks. - If
false, falls back to thecomputemethod.
- If
- Enhanced
- Playx Core (
bootCore)- Introduced new settings:
PlayxPrefsSettings: Handles configurations forcreatePlayxPrefs,createPlayxAsyncPrefs, andcreatePlayxPrefsWithCachemethods, which are now moved from thebootCoremethod.WorkManagerSettings: Supports additional configurations in thebootCoremethod.
- Introduced new settings:
- PlayxSecurePrefsSettings
- Added a
createSecurePrefsparameter to control the creation of secure storage during thebootprocess.
- Added a
Refactor
- MapAsync Extension:
- Updated the
mapAsyncandmapAsyncInIsolatemethods in theMapAsync<T>extension:mapAsyncnow takes aMapper<T, S> mapperas a required named parameter.mapAsyncInIsolatenow includes the following parameters:Mapper<T, S> mapper: Required transformation logic.bool useWorkManager: Defaults totrue. Specifies whether to useworkerManagerorcompute.
- Updated the
0.5.5 #
- refactor: Update packages.
- fix:
getDoublemethod inPlayxPrefsandPlayxAsyncPrefsreturn double not double or null. - feat: Add ColorExtensions to convert color to hex string.
0.5.4 #
- refactor: Update packages.
- refactor: Update
safe_convertmethodsasIntOr,asDoubleOr,asBoolOr,asStringOr,asListOr,asMapOr,asListTOr,asListTFromJsonOr,asListIntOr,asListStringOr,asTOrto take dynamic json instead of a Map<String,dynamic> json value. - refactor: Move json safe convert functions to a new file
- feat: Add new tests for the package.
0.5.3 #
Note: This release has breaking changes.
- Update packages.
- Update
safe_convertmethodsasInt,asDouble,asBool,asStringandasList,asMap,asListT,asListTFromJson,asListInt,asListString,asTnow throwsFormatExceptionif the result was invalid.- Added
asIntOr,asDoubleOr,asBoolOr,asStringOr,asListOr,asMapOr,asListTOr,asListTFromJsonOr,asListIntOr,asListStringOr,asTOrmethods to provide a fallback value if the result was invalid. - Added new
asListTFromJsonmethod to convert a list of dynamic values to a list of a specific type. - Added new
fromJsontoasTOrNull,asTandasTOr.
- Add new Map utilities functions to map objects in isolate.
0.5.1 0.5.2 #
- Update Readme
0.5.0 #
- Update packages.
- Added
PlayxAsyncPrefsfor non-blocking shared preferences handling. - Introduced
PlayxPrefsWithCachefor faster data retrieval with in-memory caching. - Updated PlayxCore.bootCore() to include options for initializing the new preference classes.
- Added
GetItintegration for dependency injection management. - Updated
PlayxCoreto includeGetItinstance management. - Added new
PlayxPlatformclass to provide platform-specific utilities. - Remove GetX dependency from the package.
- Remove Scope Functions from the package as there is no need for them in flutter and can be implemented if needed by a separate package.
0.4.3 #
- Update packages.
- Add a new
clearOnReinstallmethod toPlayxSecurePrefsto clear all the keys stored in the secure prefs when the app is reinstalled. - Add a new
clearOnReinstallparameter toPlayxSecurePrefsSettingsto clear all the keys stored in the secure prefs when the app is reinstalled which is set to true by default.
0.4.2 #
- Update packages.
0.4.1 #
- Add Tests for the package.
- Remove functions that check date weekDay and month from
DateExtensionsand replace them withdayOfTheWeek()andmonthOfTheYear(). - Add new
ColorExtensionsandColorUtilsto create custom utilities for colors. - Update DurationExtensions to optimize duration extensions and formatting durations.
- Add new
IterableExtensionsto add extensions likelastWhereOrNull,lastWhereOr,firstWhereOrto Iterables. - Update
PlayxEnvto not require a.envfile to be present in the project whenisOptionalis set true. - Add new
FutureExtensionsExtensions on [Future] to provide additional functionality.`
0.3.4 #
- Remove
flutter_readablepackage from dependencies. - Add more extensions to the package.
- Add safe convert methods to
PlayxCoreto convert safely convert any dynamic value to the correct type.
0.3.3 #
- Update exports.
0.3.2 #
- Update exports.
0.3.1 #
Note: This release has breaking changes.
BREAKING Changes #
PlayXCorewas renamed toPlayxCore.
New features #
- Added new IterableExtensions to add extensions like flatten, flatMap, flatAsyncMap to Iterables.
- Added new Kotlin inspired scope functions to
PlayxCorelikealso,let,run,takeIfandtakeUnless. - Added new
toBooleanextension toStringto convert string to boolean.\ - Added new example app to demonstrate the
PlayxCorefeatures.
0.2.0 #
Note: This release has breaking changes.
BREAKING Changes #
Prefswas renamed toPlayxPrefs.SecurePrefswas renamed toPlayxSecurePrefs.SecurePrefsSettingswas renamed toPlayxSecurePrefsSettings.getString,getInt,getDoubleandgetBoolmethods inPlayxPrefsnow return non nullable value of it's type with the ability to provide it with a fallback that is returned if the key not found .getString,getInt,getDoubleandgetBoolmethods inPlayxSecurePrefsSettingsnow return non nullable value of it's type with the ability to provide it with a fallback that is returned if the key not found .
New features #
- Update packages.
- Added
PlayxEnv: Wrapper for configure any the application with global variables using a.envfile`. - Update
PlayxCorebootCoremethod to takePlayxEnvSettingsparameter which is used to configureflutter_dotenvand load the.envfile. - Added new
maybeGetString,maybeGetInt,maybeGetDoubleandmaybeGetBoolmethods inPlayxPrefswhich return the value of it's type or null if the key not found or any error happened . maybeGetString,maybeGetInt,maybeGetDoubleandmaybeGetBoolmethods inPlayxSecurePrefsSettingswhich return the value of it's type or null if the key not found or any error happened .
0.1.2 #
- Move
Intlpackage,DateExtensionsandNumExtensionstoplayx_localizationpackage.
0.1.1 #
- update packages and exports.
0.1.0 #
- Enhancements to
SecurePrefs.
0.0.7 0.0.9 #
- Add
SecurePrefsto be able to store encrypted keys in the device. - Upgrade Packages.
0.0.6 #
- Add format extension for strings to format stings.
0.0.5 #
- Add support for Dart 3.0.0 and Flutter 3.10
- Upgrade Packages.
- Add multiple extensions like
DateExtensions,DurationExtensions,NumDurationExtensionsandNumExtensions. - Add common utilities.
0.0.4 #
- update Readme
0.0.3 #
- update packages
0.0.2 #
- fix typos
- add
capitalizeFirstChar(String str) - add
capitalizeFirstCharForEachWord(String str)
0.0.1 #
- initial release.