Skip to main content

cutils 0.6.3 copy "cutils: ^0.6.3" to clipboard
cutils: ^0.6.3 copied to clipboard

Flutter utility kit: money math, bytes, datetime, debounce, regex, crypto, storage, network and a log collector with optional viewer UI.

CHANGELOG #

Release notes for cutils. A short Chinese summary (中文) closes each version section; the English text is the record of note.

0.6.3 Static analysis fix: putObjectList awaits in try #

  • fix: SpUtils.putObjectList now awaits SharedPreferences.setStringList inside its try block, matching SpUtils._put's existing pattern. Resolves the unawaited_future_in_try WARNING pub.dev's analyzer reported on 0.6.2 (the only WARNING in that release's static-analysis section). Failure semantics are unchanged: errors are still caught, logged (key only - values are never logged) and mapped to false.

    中文:putObjectList 在 try 内真正 await setStringList(与 _put 同口径),消 pub.dev 分析器 unawaited-in-try WARNING;失败语义不变(捕获、仅记 key、返回 false)。

0.6.2 Packaging fix: exclude build cache and internal dist-face #

  • chore: .pubignore now excludes build/ (flutter test cache dill, 55 MB uncompressed - the bulk of the 17 MB packages 0.6.0/0.6.1 shipped), checklist.md (with its .crules-base twin) and 进阶/ - internal engineering docs were previously published into the public package (publish honours .pubignore only, not .gitignore). No code changes.

    中文:.pubignore 新增排除 build/ 测试缓存与内部分发面文档,包体 17MB→246KB;无代码变化。

0.6.1 pana fix batch (satellite branch / await semantics / dependency lower bounds) #

  • fix: NetUtils exhaustive switch now handles ConnectivityResult.satellite ("卫星网络" / satellite network). The enum member was added in connectivity_plus_platform_interface 2.1.0; missing it failed pana and downstream analyze with non_exhaustive_switch_statement (observed on the pub.dev 0.6.0 score). pubspec now declares connectivity_plus_platform_interface: ^2.1.0 explicitly to pin the transitive lower bound - a downgrade resolution to 2.0.1 was reproduced to break compilation without the declaration.

  • fix: SpUtils._put awaits the write inside try. Behavior change: write failures are caught and return false; previously the un-awaited future propagated the error to the caller.

  • fix: FileUtils.zipFiles awaits ZipFileEncoder.close(). Behavior change: since archive 3.6 close() is async finalization (the zip is complete only after the central directory is written); previously it returned without waiting. Requires the archive lower bound bump below.

  • chore: archive constraint ^3.3.7 -> ^3.6.1 (close() returns Future<void> from the 3.6 line; no in-constraint compatible call pattern exists - assigning a void result to dynamic / FutureOr both fail use_of_void, verified by downgrade analysis).

    中文:补 satellite 穷尽分支并显式锁 platform_interface ^2.1.0 下限;_put/zipFiles 改为真正 await(行为变化:失败返回 false 而非抛出,zip 收尾完才返回);archive 下限收紧 ^3.6.1。

0.6.0 TimeUtils absorbs (timespan / format parsing / AM-PM / zodiac) + DebounceUtils + review batch 1 #

  • feat: DebounceUtils throttle & debounce utility (top-level singleton debounceUtil; instances may create scoped instances). canRun is a front-edge throttle gate: first call passes and locks a cooldown window, same key rejected inside the window, default 1000ms (aligned with Blankj DebouncingUtils). debounce is a trailing-edge debounce (default 500ms). cancel clears one key, clear clears all (test isolation). Timer-map implementation, zero third-party deps (dart:async only). Empty key (after trim) or negative duration throws ArgumentError; keys share one global namespace - prefix keys with a scenario name. Design & review: docs/superpowers/specs/2026-11-25-debounce-utils-design.md.

  • feat: DateTimeUtils.formatFitTimeSpan - duration breakdown into day/hour/minute/second/millisecond with precision truncation and clamping, zero-unit skipping, negative prefix, custom units; throws ArgumentError when units length is not 5.

  • feat: DateTimeUtils.getDateTime / getDateMsByTimeStr accept an optional format - hand-written parsing with the same token set as formatDate (exact literal matching, explicit range validation preventing silent DateTime normalization, yy anchored to 2000+, missing fields default to 1970). No-argument behavior unchanged.

  • feat: DateTimeUtils.isAm / isPm.

  • feat: DateTimeUtils.getChineseZodiac(ByYear) / getZodiac(ByMonthDay) - approximated by Gregorian year/month-day (no solar-term boundary).

  • feat: RegexUtils.isMobileExact optional newSegments - dynamic validation against caller-provided new carrier segments when the static pattern misses (11-digit numeric precondition kept).

  • feat: RegexUtils.getMatches - all matches of a pattern in the input.

  • fix: LogStorage failure-path hardening - storage and rotation failures log via dart:developer instead of debugPrint (cuts the loop where a failed store is recycled by the interceptor and fails again); a broken sink is nulled before flush/close during rotation; a single old-file delete failure does not block rotation; new-file bookkeeping is guaranteed.

  • fix: getAllLogs / exportLogs duplicated results between memory and file - LogEntry gains a seq counter (assigned at enqueue on a microsecond base to avoid cross-session collisions); merged results dedupe by seq; legacy on-disk entries without seq are kept as-is.

  • fix: ExceptionInterceptor's PlatformDispatcher.onError handler forwards to a host-registered handler first and returns its verdict (previously always returned true, swallowing the host decision); behavior unchanged when no handler is registered.

  • fix: LogCollector.initialize failure rollback - if storage or interceptor startup throws, it stops started interceptors, removes outputs and interceptors added this round, restores config/storage and rethrows; no half-initialized state (retries no longer double-register).

  • fix: DateTimeUtils.getBusinessDate converts UTC inputs to the local timezone before comparing against the day-cut line (the cut line is local wall-clock semantics; unchanged when cutoffTime is absent).

  • fix: UuidUtils.generateV5 cache key is now namespace|name (previously cached by name only - same name under different namespaces returned the wrong UUID); cache caps at 1024 and evicts the oldest.

  • fix: KeyboardUtils.analysisKeyEvent numpad handling - numpad0-9 and operator keys carry keyIds in the high region (>255) and were filtered to an empty string; the high-region branch now attempts numpad resolution (character -> physical key map) before giving up.

    中文:DebounceUtils 防抖节流;DateTimeUtils 四件(时长拆解/format 解析/上下午/生肖星座);RegexUtils 新号段与 getMatches;log_collector 六项失败路径加固;getBusinessDate UTC 折算、generateV5 缓存串台修复、小键盘识别修复。

0.5.0 Log viewer (floating ball + panel) #

  • feat: log viewer (floating ball + panel) - new view/ family and RouteLogObserver, exported via log_collector_export.dart into the top-level barrel (new public symbols: attachViewer / LogViewerController / loadViewerLogs / ViewerBridgeOutput / LogViewerPanel / LogViewerPanelState / LogViewerEntryTile / LogViewerTheme / RouteLogObserver).

  • feat: LogCollectorHelper.network() unified network logging (level derived from statusCode; extra always carries the same six keys).

  • feat: LogSource enum gains route (downstream code not calling the new API is unaffected).

  • feat: FileLogOutput fully implemented (the constructor used to throw UnimplementedError; now a working file output, signature unchanged: filePath / maxFileSize / maxFileCount) - line-by-line append writing (entry.toString() text lines, not a parsed format), lazy IOSink open (parent directories auto-created), in-memory byte tracking, rotation on exceeding maxFileSize (_yyyy-MM-dd_HHMMss timestamp suffix, no dangling dot for extension-less paths), oldest-file deletion beyond maxFileCount by exact base-name prefix match, dispose safeguards, and errors reported via developer.log (not debugPrint, avoiding a loop with the default DebugPrintInterceptor). Two caveats: on web the whole log_output.dart (incl. ConsoleLogOutput / BatchLogOutput) does not compile due to dart:io; no periodic flush (flush happens on rotation and dispose only - abnormal process death may lose the tail buffer).

    中文:日志查看器(悬浮球+面板)及新公开符号面;网络打点 helper;LogSource 增 route;FileLogOutput 占位实装(逐行追加/惰性 sink/轮转归档);注意 web 端 log_output.dart 不可编译、无周期 flush。

0.4.0 saas_pos absorbs (version compare / LAN IPv4 / masking family / business day / SP self-heal / SHA & HMAC) #

Six capabilities absorbed from saas_pos_smart_edition (POS client) by "absorb and rewrite" - no file copies: everything re-written on this repo's baseline, silent error swallowing replaced with explicit throws, private benefits generalized into utilities.

  • New lib/system/version_utils.dart: VersionUtils.compare / isNewer

    • three-way dotted version comparison (strips v/V prefix, per-segment numeric order, trailing zeros equal so 1.0 == 1, missing segments sort lower). Empty input throws ArgumentError (previously silently returned false). Pre-release labels are not parsed (1.0.0-beta equals 1.0.0).
  • New lib/net/lan_utils.dart: LanUtils.getPreferredLanIpv4 - preferred LAN IPv4 (192.168 > 10 > 172.16-31 > others; loopback/APIPA excluded, virtual adapters de-prioritized but not excluded); returns null without network, never throws. Unavailable on web (dart:io).

  • StringExt masking family upgraded (lib/ext/string_ext.dart):

    • maskMobile tiered masking (>=10 digits: first 3 last 4 / 7-9: first 2 last 2 / 4-6: first 1 last 1 / <4: unchanged; country-code prefix kept and re-joined with a space; tier decided by digit count). Behavior change: the old implementation only worked for exactly 11 digits and returned anything else untouched (a privacy leak). Non-11-digit inputs are now tier-masked, and the mask body is rebuilt from digits only - non-digit characters (e.g. - separators) are no longer preserved, so 11-digit inputs containing noise change output too.
    • New maskMobileOr / maskMiddle / maskMiddleOr (generic head/tail masking; negative arguments throw ArgumentError).
  • DateTimeUtils.getBusinessDate (lib/datetime/date_utils.dart): business-day attribution - attributes a checkout moment to its business-day anchor via an "HH:mm:ss" day-cut line (the returned anchor is the cut moment, not midnight of the date); returns the input unchanged without a cut line; an invalid cut line throws ArgumentError (previously swallowed).

  • Windows SP file self-heal (lib/storage/sp_util.dart + sp_backup_io.dart / sp_backup_none.dart): after a successful SpUtils.init() the shared_preferences.json is backed up; on init failure the backup is validated (a legal JSON object) before being restored (validate-then-replace, keep the scene on failure); rethrow semantics unchanged; backup/restore IO failures only log. Platform surface change: sp_util now conditionally imports dart:io (web uses a no-op stub - backup/restore entries are no-ops on web); no-op on non-Windows platforms. The file layout is coupled to shared_preferences_windows 2.4.1 defaults.

  • CryptoUtils new digests / signatures (lib/crypto/crypto_utils.dart): encodeSha256 (lowercase hex), encodeHmacSha1 / encodeHmacSha256 (utf8 input, lowercase hex by default, base64: true for standard base64).

    中文:六件自 saas_pos 吸收重写:版本比较、首选局域网 IPv4、脱敏族升级(maskMobile 分级脱敏,行为变化)、营业日归属、Windows SP 自愈(条件 import 引入 dart:io)、SHA256/HMAC。

0.3.0 YCFlutterUtils absorbs (byte utils / yuan-to-cents / validators) #

Three capabilities absorbed from YCFlutterUtils by "absorb and rewrite" - the source is pre-null-safety code with defects; everything was rewritten on this repo's baseline with fixes:

  • New lib/byte/ byte utilities module (zero third-party deps, only dart:typed_data / dart:convert): ByteUtils - readable string <-> Uint8List (hex/dec with value validation rejecting tokens above 0xFF, no silent truncation), base64 conversion, clone/equality and window ops (slice/concat/insert/delete with bounds clamping, inputs unmodified); ByteWord / ByteDoubleWord - 16/32-bit integers split and packed per explicit Endian.

  • MoneyUtils.changeY2F(String) -> int yuan-to-cents: symmetric with changeF2Y; Decimal end-to-end without going through double (no precision loss beyond the 2^53 boundary); unparseable input, non-integral cents, or results beyond the platform int range throw ArgumentError.

  • RegexUtils 15 new validators with matching REGEX_* constants: file-type family of 11 (isImage / isAudio / isVideo / isTxt / isDoc / isExcel / isPpt / isApk / isPdf / isHtml / isVector - extension heuristics, double-anchored with escaped separator dots, case insensitive), hash format family of 3 (isMD5 / isSHA1 / isSHA256 - format-only checks, no checksum verification; colon-separated forms supported), and isHexadecimal (bare hex string - different semantics from isHexColor).

    中文:字节工具模块(可读串互转/端序拆装/窗口操作)、元转分(全程 Decimal 不经 double)、正则 15 个校验方法与配套常量(文件类型族/哈希族/十六进制)。

0.2.1 Per-entry console suppression for log_collector #

LogEntry gains a suppressConsole flag (default false, existing behavior unchanged): flagged entries still enter the pipeline (memory + file, visible via getLogs / export) but console-type outputs skip them on dispatch - for low-value, high-frequency logs in release builds (keep the archive, skip the noise).

  • The six level helpers on LogCollectorHelper (log / debug / info / warning / error / fatal) pass the flag through an optional parameter.

  • The LogOutput base class gains an isConsole contract getter (default false): custom outputs writing to the console must override it to true; wrapper/delegating outputs must forward delegate.isConsole (ConsoleLogOutput / BatchLogOutput already implement it correctly).

  • Semantics: does not retroactively suppress original output already sent to the console by interceptors (e.g. raw debugPrint); the flag is an in-process routing hint only and is not persisted in toJson.

  • Reviewed via an independent review loop (docs/评审-plan-log-suppress-console.md); 15 new test cases (test/log_collector/log_collector_suppress_console_test.dart).

    中文:LogEntry 增 suppressConsole 条目级压制(仅跳过控制台分发,档案照写);六个级别方法透传;LogOutput 增 isConsole 契约;新增 15 个测试。

0.2.0 Naming unification (breaking) #

All utility classes unified to the *Utils suffix (21/21), removing the Util/Utils double track and two misspellings. File names and import paths are unchanged; top-level lowercase instances (spUtil / netUtil / eventBus / deviceInfo / packageInfoUtil / logger) unchanged; no old-name aliases kept (pre-1.0 with no existing downstream - aliases would only prolong the double track). Rename call sites per the table.

Old New
UUIDUtils UuidUtils
KeyBoardUtils KeyboardUtils
NetUtil NetUtils
TimerUtil TimerUtils
SpUtil SpUtils
TimelineUtil TimelineUtils
DeviceInfoUtil DeviceInfoUtils
EventBusUtil EventBusUtils
PackageInfoUtil PackageInfoUtils

Docs

  • Module headers now declare dependencies (the platform plugin surface is explicit, flagging downstream integration/stub cost) plus a log/ <-> log_collector/ dual-track positioning note; log_collector's dependency on path_provider via log_storage is stated explicitly.

    中文:21 个工具类统一 *Utils 后缀(破坏性改名,不保留别名,按表改调用点);文件名与 import 路径不变;模块头补依赖标注。

0.1.0 Restructure and quality pass (breaking) #

Restructured from a plugin package into a pure Dart/Flutter utility library; directory structure and public API overhauled; a batch of high-severity bugs fixed. Pre-1.0 - APIs may evolve.

Restructure

  • Downgraded from plugin to a plain Dart/Flutter package (removed method_channel / platform_interface / android / ios / scaffold tests, neutralized example).
  • New top-level barrel lib/cutils.dart - one import for all core tools: import 'package:cutils/cutils.dart';.
  • Directory moves: date/ + time/ -> datetime/; encrypt/ -> crypto/; sp/ -> storage/; dissolved the utils/ grab-bag -> event/ + ui/ + identifier/; text/ split into ui/ + ext/.
  • Removed hardware dead code: scanner/, system/serial_util (deferred to a separate sub-package cutils_pos).
  • Cleaned dead dependencies and the pubspec plugin section; removed dartx (one .filter usage migrated to dart:core where; the StringExt.isNullOrEmpty conflict with its own extension is resolved).

API style (stateless tools become static classes)

The stateless utilities below moved from "instance + singleton" to static classes; call sites change from xUtils.foo() to XUtils.foo(): NumUtils, DateTimeUtils, CryptoUtils, JsonUtils, RandomUtils, UUIDUtils, KeyBoardUtils, RegexUtils, MoneyUtils. Stateful singletons kept: spUtil, logCollector, eventBus, netUtil, deviceInfo, packageInfoUtil, logger.

Renames

  • NumUtils exact-arithmetic family (addDec / subtractDec / multiplyDec / divideDec / remainder and the matching *DecString variants) now returns String? (a decimal string) instead of Decimal? - Decimal is internal again and no longer appears in public signatures (downstream no longer needs the decimal package directly). Failure semantics unchanged (parse failure / division by zero still return null).
  • SpUtil.init() returns Future<bool> (was Future<SharedPreferences?>; true on success, throws on failure) - the SharedPreferences object is no longer exposed; use getSp() when the raw instance is needed.
  • moneyFormatWithUnit (StringExt / DoubleFormating) now computes via Decimal (same strategy as formatMoney) - no precision loss near the 2^53 boundary; exotic inputs that Decimal cannot parse fall back to the old double path (behavior compatible).
  • DateUtils -> DateTimeUtils (avoiding the Flutter SDK DateUtils name clash); EncryptUtils -> CryptoUtils; printJson -> logJson (with a @Deprecated alias); putObject -> putJsonable (with a @Deprecated alias); TimerUtil.updateTotalTime becomes a pure setter (no implicit restart), new restart() carries the old behavior.

Semantic / behavior changes

  • Regex: REGEX_INTEGER / REGEX_FLOAT and friends fully anchored ("123abc" no longer false-positives); REGEX_EMAIL non-backtracking with a 254 cap (looser and ReDoS-resistant); isURL / isIP fully anchored; isNumeric("123.") -> false; isJSON tightened to object / array only.
  • Numbers: NumUtils.*Num() throws ArgumentError on non-finite input (was a silent 0.0); divideDec(1, 3) no longer throws.
  • Money: MoneyUtils.changeF2Y* throws ArgumentError on invalid input or overflow (was a raw FormatException); large amounts are formatted via Decimal.
  • Crypto: CryptoUtils.xorBase64* encodes the raw UTF-8 bytes as base64 (the code-unit path threw on surrogate pairs); encodeMd5File is streaming (reading as a string corrupted binary hashes).
  • File: createFileFromBase64 throws a typed InvalidBase64Exception.
  • System: KeyBoardUtils.closeKeyBoard no longer hides system UI (the immersive side effect is removed); NetUtil: Windows no longer hardcoded online, Bluetooth counts as online, multi-result aggregation (any non-none result = online).
  • Extensions: double_ext.percentFormat multiplies by 100; object_ext.isNullOrBlank no longer treats 0 as empty; int_ext.currencyFormatWithSymbol drops the space after the symbol; string_ext.formatMoney no longer appends .0 for whole yuan.
  • Datetime: DateTimeUtils.nextMonth returns DateTime (was int); getYesterday is calendar-day (DST-correct); isToday / isWeek no longer treat ms == 0 as "no value".
  • JSON: JsonUtils.encodeObjectList([]) returns "[]" (was null).

Deletions (unused, zero callers)

  • 14 lowercase regex constants (email / url / hexadecimal / vector / image / audio / video / txt / doc / excel / ppt / apk / pdf / html).
  • net/url_utils.dart (empty UrlUtils); ext/bool_ext.then; TimelineInfo.weeks.

High-severity fixes (abridged)

  • log_collector: FlutterError recursion / no-op rotation / Timer leaks / dispose not releasing outputs / unbounded queue / init race / ConsoleLogOutput using print.

  • file_utils: readBySink empty returns / cleanExpiredLog using .millisecond causing random deletions / several un-awaited futures / deleteLog ignoring saveDays / path traversal / getFileList and deleteLog enumeration switched to suffix matching plus directory-link exclusion (substring matching collected *.log.bak and directories named *.log, and zipping those threw) / cleanLog excludes directory links (an empty *.log directory was silently deleted) / expiry check switched from ctime to mtime.

  • datetime: SSS millisecond formatting / isToday isUtc / countdown drift / uncanceled Future.delayed.

  • system: winUniqueIdentifier mixing in DateTime.now / navigationBarHeight formula.

  • ext: thousands-separator negatives / undisposed TextPainter / sp logging values into logs (PII).

    中文:自 plugin 重组为纯工具库(顶层 barrel、目录重组、移除硬件死代码与死依赖);无状态工具转静态类;签名变更(*Dec 族改返回 String?、init 返回 bool、若干改名);正则/数值/金额/加解密/文件/系统/扩展/日期/JSON 全面语义修复;删除零调用死代码;高危 bug 修复清单见英文段。

0.0.1 #

Initial placeholder release (plugin scaffold).

中文:初始占位版本(plugin 脚手架)。

1
likes
140
points
205
downloads

Documentation

API reference

Publisher

unverified uploader

Weekly Downloads

Flutter utility kit: money math, bytes, datetime, debounce, regex, crypto, storage, network and a log collector with optional viewer UI.

Repository (GitHub)
View/report issues

License

MIT (license)

Dependencies

archive, connectivity_plus, connectivity_plus_platform_interface, convert, crypto, decimal, device_info_plus, event_bus, file, flutter, logger, package_info_plus, path, path_provider, shared_preferences, uuid

More

Packages that depend on cutils