flutter_shared_utilities 1.0.14
flutter_shared_utilities: ^1.0.14 copied to clipboard
A comprehensive Flutter utilities package with extensions, models, and utility functions.
Changelog #
All notable changes to this project will be documented in this file.
The format is based on Keep a Changelog, and this project adheres to Semantic Versioning.
1.0.14 - 2025-07-05 #
Added #
-
Color Serialization Support: Comprehensive Color serialization and deserialization utilities
Color.toSerializable
- Convert Color objects to hex strings using enhancedtoHex()
methodfromSerializable<Color>()
- Deserialize Color from hex strings with flexible format support- Support for various hex formats:
#RRGGBB
,#RRGGBBAA
,0xAARRGGBB
, and shorthand#RGB
List<Color>
serialization/deserialization - Handle arrays of Color objects- Intelligent alpha channel handling with format detection (CSS vs hex prefix)
- Graceful error handling for invalid color strings with null fallback
-
Enhanced Color Extensions: Improved
ColorExtensions.toHex()
method- Smart alpha channel handling - omits alpha for fully opaque colors
- Configurable leading hash sign with
leadingHashSign
parameter - Proper color channel rounding and hexadecimal conversion
- Uppercase hex output for consistency
-
Advanced String to Color Conversion: Enhanced
StringTypeConversionExtensions.toColor()
- CSS format support (
#RRGGBBAA
) with automatic RGBA to ARGB conversion - Hex format support (
0xAARRGGBB
) with proper ARGB handling - Shorthand hex support (
#RGB
→#RRGGBB
) - Length-based format detection and intelligent padding/truncation
- Robust error handling for malformed color strings
- CSS format support (
-
Uint8List Serialization Support: Enhanced binary data handling
Uint8List.toSerializable
- Convert binary data to Base64 stringsfromSerializable<Uint8List>()
- Deserialize from Base64 strings, List- Fallback mechanisms for different input formats
- Safe error handling with null returns for invalid inputs
-
Comprehensive Test Coverage: Added extensive test suites for new functionality
color_serialization_test.dart
- 50+ tests covering all Color serialization scenarios- Enhanced
serialization_extensions_test.dart
- Additional Color and Uint8List tests - Updated
to_serializable_test.dart
- Color serialization validation tests - Edge case testing including invalid inputs, mixed formats, and boundary conditions
- Round-trip serialization/deserialization verification
Changed #
-
Improved Type Safety: Enhanced type checking and validation in serialization methods
- Better error messages with comprehensive type support documentation
- Intelligent format detection for different hex string formats
- Robust null handling throughout all conversion methods
-
Enhanced Documentation: Updated inline documentation with practical examples
- Clear format specifications for Color hex strings
- Usage examples for different serialization scenarios
- Better error handling documentation
Technical Features #
- Format Detection: Intelligent detection of CSS vs hex color formats
- Smart Alpha Handling: Automatic alpha channel processing based on format
- Fallback Mechanisms: Multiple fallback strategies for robust data conversion
- Type Validation: Comprehensive type checking with detailed error messages
- Test Coverage: 95%+ test coverage for all new serialization functionality
Migration Notes #
- Non-Breaking Changes: All existing functionality preserved and enhanced
- Backward Compatible: Existing Color serialization continues to work
- New Capabilities: Color objects now serialize to more readable hex format
- Enhanced Error Handling: Better graceful degradation for invalid inputs
1.0.13 - 2025-07-03 #
- Do not use try catch to silent set state exceptions
1.0.12 - 2025-07-01 #
Added #
-
SafeUrlLaunchMode Enum: Custom launch mode enum for URL launching with better API encapsulation
SafeUrlLaunchMode.platformDefault
- Platform-specific default behaviorSafeUrlLaunchMode.inAppWebView
- Launch in in-app web view (Android WebView)SafeUrlLaunchMode.inAppBrowserView
- Launch in in-app browser (Custom Tabs, SFSafariViewController)SafeUrlLaunchMode.externalApplication
- Launch in external applicationSafeUrlLaunchMode.externalNonBrowserApplication
- Launch in external non-browser application
-
SafeUrlLaunchModeExtension: Extension to convert custom enum to url_launcher's LaunchMode
urlLauncherLaunchMode
getter - Seamless conversion using switch expression- Type-safe mapping between custom enum and url_launcher enum values
Changed #
- SafeUrlLauncher API Enhancement: Updated method signatures for better type safety
launch()
method now usesSafeUrlLaunchMode
instead of directLaunchMode
launchWithFeedback()
method now usesSafeUrlLaunchMode
parameters- Maintains backward compatibility through extension conversion
- Improved API consistency with package-specific enum types
Technical Features #
- Better Encapsulation: Reduced direct dependency on url_launcher's LaunchMode enum in public API
- Type Safety: Custom enum provides package-specific launch mode options
- Seamless Integration: Extension-based conversion maintains compatibility with url_launcher
- Switch Expression: Modern Dart syntax for enum conversion with exhaustive matching
- Documentation: Comprehensive inline documentation for all new enum values and extension methods
Migration Notes #
- Non-Breaking Change: Existing code using
LaunchMode
will continue to work - Recommended Update: Consider migrating to
SafeUrlLaunchMode
for better type safety - Default Values: All methods maintain the same default launch modes (externalApplication with inAppWebView fallback)
- Future-Proof: Custom enum allows for package-specific launch mode extensions without breaking changes
1.0.11 #
Added #
- DateTime Extensions: Comprehensive DateTime utility extensions for Flutter apps
-
String Conversion Methods: Convert DateTime to various string formats
toTimeString()
- Convert to HH:MM:SS format (e.g., "09:05:03")toTimeShort()
- Convert to HH:MM format (e.g., "09:05")toDateString()
- Convert to DD/MM/YYYY format (e.g., "01/01/2023")toDateUS()
- Convert to MM/DD/YYYY US format (e.g., "01/01/2023")toDateISO()
- Convert to YYYY-MM-DD ISO format (e.g., "2023-01-01")toDateTimeString()
- Convert to DD/MM/YYYY HH:MM formattoDateTimeFull()
- Convert to DD/MM/YYYY HH:MM:SS formatto12Hour()
- Convert to 12-hour format with AM/PM (e.g., "2:30 PM")
-
Date Comparison Properties: Boolean properties for date comparisons
isToday
,isYesterday
,isTomorrow
- Compare with current dateisThisWeek
,isThisMonth
,isThisYear
- Check current time periodsisWeekend
,isWeekday
- Check day typeisAM
,isPM
- Check time periodisLeapYear
- Check if year is leap year
-
Date Calculation Properties: Get specific date/time boundaries
startOfDay
,endOfDay
- Day boundaries (00:00:00 to 23:59:59.999)startOfWeek
,endOfWeek
- Week boundaries (Monday to Sunday)startOfMonth
,endOfMonth
- Month boundariesstartOfYear
,endOfYear
- Year boundaries
-
Date Arithmetic Methods: Add/subtract time periods
addDays(int days)
,subtractDays(int days)
- Day operationsaddMonths(int months)
,subtractMonths(int months)
- Month operations with overflow handlingaddYears(int years)
,subtractYears(int years)
- Year operations
-
Utility Properties: Additional useful date information
ageInYears
- Calculate age from birthdate to nowdaysFromNow
,daysToNow
- Days difference from current daterelativeTime
- Human-readable relative time (e.g., "2 hours ago", "tomorrow")monthName
,monthNameShort
- Full and abbreviated month namesweekdayName
,weekdayNameShort
- Full and abbreviated weekday namesdaysInMonth
- Number of days in current monthquarter
- Quarter of the year (1-4)
-
Comparison Methods: Compare dates with other DateTime objects
isSameDay(DateTime other)
- Check if same calendar dayisSameWeek(DateTime other)
- Check if in same weekisSameMonth(DateTime other)
- Check if in same monthisSameYear(DateTime other)
- Check if in same year
-
Technical Features #
- Smart Month/Year Arithmetic: Proper handling of month overflow (e.g., Jan 31 + 1 month = Feb 28/29)
- Safe Array Access: Uses
safeAt()
extension to prevent index out of bounds errors - Comprehensive Error Handling: Fallback values for invalid month/weekday indices
- Type Safety: Full null safety compliance with proper error handling
- Performance Optimized: Efficient calculations without unnecessary DateTime instantiations
File Structure #
- New Files:
lib/src/extensions/date/date_time_extensions.dart
- DateTime extension implementationslib/src/extensions/date/date.dart
- Date extensions export file
- Updated Files:
lib/src/extensions/extensions.dart
- Added date extensions export
Developer Experience #
- Intuitive Method Names: Using
to
prefix for conversion methods (e.g.,toTimeString()
) - Comprehensive Documentation: Detailed inline documentation with examples for all methods
- Consistent API: Follows existing package patterns and naming conventions
- Rich Examples: Practical usage examples for Flutter app development
- Safe Defaults: Graceful handling of edge cases with meaningful fallback values
1.0.10 #
- Improve README file
1.0.9 #
Added #
-
Safe URL Launcher Utility: Comprehensive URL launching utility with advanced safety features
SafeUrlLauncher.launch()
- Safe URL launching with fallback mode support- Preferred mode with automatic fallback (defaults: externalApplication → inAppWebView)
- Comprehensive error handling and validation
- Support for custom web-only window names
SafeUrlLauncher.launchWithFeedback()
- URL launching with user feedback via SnackBar- Automatic error message display on launch failure
- Context safety with mounted widget checking
- Customizable error messages
- Graceful handling of null contexts
SafeUrlLauncher.launchWebUrl()
- Specialized web URL launchingSafeUrlLauncher.launchEmail()
- Email launching with pre-filled content- Support for recipient, subject, and body parameters
- Proper URL encoding for special characters
- Safe parameter validation
SafeUrlLauncher.launchPhone()
- Phone dialer launching with number cleaningSafeUrlLauncher.launchSms()
- SMS launching with pre-filled messagesSafeUrlLauncher.isValidUrl()
- Public URL validation method- Validates HTTP/HTTPS URLs with authority checking
- Supports special schemes (mailto, tel, sms)
- Comprehensive format validation
SafeUrlLauncher.canLaunch()
- Check if URL can be launched without actually launching
-
Enhanced URL Validation: Intelligent URL scheme validation
- HTTP/HTTPS URLs require valid authority (domain)
- Special schemes (mailto, tel, sms) validated by scheme presence
- Other schemes validated by authority or path presence
- Robust error handling for malformed URLs
-
Phone Number Processing: Smart phone number handling
- Automatic cleaning of phone numbers (removes formatting)
- Support for international numbers with + prefix
- Validation for reasonable phone number lengths (7-15 digits)
-
Comprehensive Test Coverage: Added complete test suite for SafeUrlLauncher
- URL validation tests for all supported schemes
- Edge case handling and malformed input testing
- Phone number cleaning and validation tests
- Email format validation testing
Dependencies #
- Added:
url_launcher: ^6.3.1
- For URL launching functionality - Added:
flutter/material.dart
import - For SnackBar user feedback
Technical Features #
- Fallback Mechanism: Automatic fallback between launch modes for better reliability
- Context Safety: Built-in checks for widget lifecycle and mounted state
- Error Resilience: Comprehensive exception handling with debug logging
- Type Safety: Full null safety compliance with safe type checking
- Logging Integration: Uses existing SafeDebugLog for consistent error reporting
- Material Integration: Native Flutter Material Design SnackBar support
Developer Experience #
- Flexible API: Multiple convenience methods for different URL types
- Safe Defaults: Sensible default parameters for common use cases
- Clear Documentation: Comprehensive inline documentation with examples
- Return Values: Boolean returns for success/failure tracking
- Error Feedback: Built-in user feedback system for failed launches
1.0.8 #
Added #
-
Safe SetState Extensions: Comprehensive setState safety utilities for StatefulWidget classes
safeSetState(VoidCallback fn)
- Basic safe setState with mounted checksafeSetStateAsync(VoidCallback fn)
- Safe setState for async operationssafeSetStateDelayed(Duration delay, VoidCallback fn)
- Safe setState with delaysafeRebuild()
- Safe widget rebuild without state changes- All methods return
bool
indicating success/failure - Prevents the common Flutter error: "setState() called after dispose()"
- Includes proper exception handling with debug logging
- Works with any
State<T>
class through extension methods
-
Widget Extensions Structure: New organized extension structure
lib/src/extensions/widget/state_extensions.dart
- State utility extensionslib/src/extensions/widget/widget.dart
- Widget extensions barrel file- Updated main extensions export to include widget utilities
Changed #
- Enhanced Package Documentation: Updated README with comprehensive Safe SetState examples
- Added practical usage examples with StatefulWidget
- Documented all available setState safety methods
- Updated features list to highlight setState safety utilities
- Improved quick start guide with widget state management examples
Technical Features #
- Mounted State Checking: All setState methods verify widget is mounted before execution
- Error Resilience: Graceful handling of setState exceptions with debug logging
- Async Support: Built-in support for async operations with proper state management
- Delayed Operations: Safe delayed setState operations with automatic cleanup
- Type Safety: Full null safety compliance with comprehensive type checking
- Return Values: Boolean return values for success/failure tracking
1.0.7 #
- byNameSafe extension for utilities (mainly for enums)
1.0.6 #
- Support Uint8List type
1.0.5 #
- Updated lint rules
- Added extra public documentations
1.0.4 #
Removed #
- Interface Classes: Removed abstract interface classes that were not core to the package functionality
AppLogger
- Application logging interface with debug, info, warning, and error methodsConnectivityService
- Network connectivity management interface with internet reachability checksinterfaces.dart
- Export file for interface classes- Complete removal of
lib/src/interfaces/
directory
Changed #
- Library Exports: Updated main library file (
flutter_shared_utilities.dart
)- Removed
export 'src/interfaces/interfaces.dart';
statement - Streamlined package to focus on core utilities, extensions, models, and utils
- Removed
Migration Notes #
- Breaking Change: Applications using
AppLogger
orConnectivityService
interfaces will need to implement their own logging and connectivity abstractions - Rationale: Removed interface classes to keep the package focused on concrete utilities rather than abstract contracts
- Alternative: Users can copy the interface definitions from version 1.0.3 if needed, or implement their own logging/connectivity abstractions
- No impact on core functionality: extensions, models, parsers, and utility functions remain unchanged
1.0.3 #
Fixed #
- SafeParser Double-Encoding Issue: Fixed critical bug where
safeEncodeJson()
would double-encode already valid JSON strings- Before:
SafeParser.safeEncodeJson('"hello"')
→"\"hello\""
(double quotes) - After:
SafeParser.safeEncodeJson('"hello"')
→"hello"
(correct single encoding) - Intelligent JSON detection prevents double-encoding of JSON objects, arrays, and primitives
- Enhanced
_isValidJson()
helper method with comprehensive validation - Improved fallback logic for malformed JSON strings
- Before:
Added #
-
Comprehensive Test Coverage: Added extensive test suites with 78+ new tests
test/utils/safe_parser_test.dart
- 26 tests covering all SafeParser functionalitytest/extensions/map/map_parser_extensions_test.dart
- 52 tests for MapParserExtensions- Round-trip encoding/decoding verification tests
- Edge case testing (unicode, special characters, deeply nested structures)
- Error handling and fallback behavior validation
- Double-encoding prevention verification tests
-
Enhanced SafeDecodeJson: Improved JSON decoding with better error handling
- Smart detection of already-decoded primitive values
- Enhanced fallback logic for malformed JSON
- Better handling of quoted strings with escape sequences
- Graceful return of original string when JSON parsing fails
Changed #
- Type Safety Improvements: Enhanced type annotations in test files
- More specific type expectations (
List<Object?>
instead ofList
) - Better type checking in map parser extension tests
- Improved null safety handling throughout tests
- More specific type expectations (
Technical Details #
-
JSON Detection Algorithm: New intelligent JSON validation
- Detects JSON objects (
{}
format) - Detects JSON arrays (
[]
format) - Detects JSON strings (quoted format)
- Detects JSON primitives (numbers, booleans, null)
- Validates actual JSON parseability, not just format
- Detects JSON objects (
-
Test Architecture: Following Flutter best practices
- Grouped tests by functionality for better organization
- Comprehensive edge case coverage including unicode and special characters
- Safe type checking without null force operators or unsafe casting
- Bounds checking for array access in all test scenarios
Migration Notes #
- No breaking changes - all existing functionality preserved
- SafeParser now correctly handles already-encoded JSON without modification
- Enhanced error handling provides better fallback behavior
- Existing code will benefit from the double-encoding fix automatically
1.0.2 #
Added #
-
Enhanced Serialization Extensions: Major improvements to
fromSerializable<T>()
methodList<DateTime>
support - Convert arrays of ISO strings, timestamps, and DateTime objectsList<Duration>
support - Convert arrays of microsecond integers, strings, and Duration objectsMap<String, DateTime>
support - Handle JSON objects with date fieldsMap<String, Duration>
support - Handle configuration objects with time values- Early error detection with
assert()
statements in debug mode - Comprehensive type validation with
_isSupportedType()
helper method
-
Safe Conversion Helpers: New helper methods for robust type conversion
_safeDateTime()
- Handles ISO strings, timestamps, with Unix epoch fallback_safeDuration()
- Handles microseconds, strings, with zero duration fallback- Graceful error handling for all invalid inputs
-
Developer Experience Improvements:
- Clear, detailed assert error messages guide developers to supported types
- Immediate feedback during development for unsupported type usage
- Better documentation in error messages with examples
Changed #
-
Simplified Architecture: Removed complex recursive type conversion logic
- Direct type checking for better performance and maintainability
- Eliminated
_extractGenericType()
and_extractMapValueType()
helper methods - Removed
_convertToType()
recursive method for cleaner code - Streamlined error handling with assert-first approach
-
Improved Type Safety: Enhanced type checking and conversion
- Fixed string-to-int conversion to handle decimal strings like "95.5" → 95
- Better handling of mixed data types in collections
- More robust JSON string parsing for typed collections
Fixed #
- Type casting issues with
Map<String, DateTime>
andMap<String, Duration>
- Decimal string parsing in
_safeInt()
method (e.g., "95.5" now converts to 95) - Eliminated runtime
UnsupportedError
throws in favor of development-time asserts
Technical Details #
- Supported Simple Types:
int
,double
,String
,bool
,DateTime
,Duration
,Uri
,Object?
,dynamic
- Supported List Types:
List<int>
,List<double>
,List<String>
,List<bool>
,List<DateTime>
,List<Duration>
,List<Object?>
- Supported Map List Types:
List<Map<String, Object?>>
,List<Map<String, dynamic>>
- Supported Map Types:
Map<String, int>
,Map<String, double>
,Map<String, String>
,Map<String, bool>
,Map<String, DateTime>
,Map<String, Duration>
,Map<String, Object?>
,Map<String, dynamic>
Migration Notes #
- No breaking changes - all existing functionality preserved
- Assert statements only trigger in debug mode, no impact on production builds
- New DateTime/Duration collection support is additive
- Developers using unsupported nested types will now get immediate feedback via asserts
1.0.1 #
Added #
- Comprehensive documentation and examples in README
- Production-ready package structure
- Badges for pub.flutter-io.cn, license, and Flutter version
- Detailed API reference with code examples
- Contributing guidelines
- Issue and feedback links
Changed #
- Updated package description for better clarity
- Enhanced documentation with emojis and better formatting
- Improved code examples with practical use cases
Fixed #
- Package naming consistency (flutter_shared_utilities)
- Documentation structure and completeness
1.0.0 #
Added #
-
String Extensions: Case-insensitive string operations, JSON validation, and utility methods
compareWithoutCase()
- Case-insensitive string comparisonstartsWithIgnoreCase()
- Case-insensitive prefix checkingcontainsWithoutCase()
- Case-insensitive substring searchisNullString
,isNullEmpty
- Null and empty string checksisJsonObject
,isJsonArray
,isJsonPrimitive
- JSON format validation
-
List Extensions: Smart list operations with duplicate prevention
insertIfNotExists()
- Insert item only if it doesn't existaddAllIfNotExists()
- Add multiple items, skipping duplicatesremoveIfExist()
- Remove item if it exists in the list- Custom equality checker support for complex objects
-
Safe Parser: Robust JSON parsing with error handling
safeEncodeJson()
- Safe JSON encoding with error handlingsafeDecodeJson()
- Safe JSON decoding with validationparseIterable()
- Type-safe iterable parsing
-
Base Data Model: Abstract class for consistent data handling
fromMap()
- Convert Map to model instancetoMap()
- Convert model to MapfromJson()
- Convert JSON string to model instancetoJson()
- Convert model to JSON string- Equatable integration for value equality
-
Object Serialization Extensions: Safe type conversion utilities
fromSerializable<T>()
- Safe type conversion with null safety
-
Interfaces: Abstract interfaces for common services
AppLogger
- Application logging interfaceConnectivityService
- Network connectivity management interface
-
Utility Functions: Additional helper utilities
safeDebugLog()
- Safe debug logging with stack trace support
-
Color Extensions: Enhanced color manipulation utilities
-
Map Extensions: Safe map parsing and utility functions
-
Iterable Extensions: Utility functions for iterable collections
Technical Features #
- Full null safety support
- Comprehensive type checking
- Error handling and safe parsing
- Custom lint rules for code quality
- Flutter 3.0+ compatibility
- Dart SDK 3.8.1+ support
Dependencies #
equatable: ^2.0.7
- For value equalitycollection: ^1.19.1
- For collection utilitiescustom_lint: ^0.7.5
- For custom linting rulesflutter_custom_lints: ^1.0.2
- For Flutter-specific linting