flutter_shared_utilities 1.0.7
flutter_shared_utilities: ^1.0.7 copied to clipboard
A comprehensive Flutter utilities package with extensions, models, and utility functions.
flutter_shared_utilities #
A comprehensive Flutter utilities package that provides essential extensions, models, and utility functions to streamline your Flutter development workflow. This package includes safe parsing utilities, string manipulation extensions, list operations, and more.
β¨ Features #
- π§ Safe Parsing: Robust JSON parsing with double-encoding prevention and error handling
- π String Extensions: Case-insensitive comparisons, JSON validation, and utility methods
- π List Utilities: Smart list operations with duplicate prevention
- π¨ Color Extensions: Enhanced color manipulation utilities
- πΊοΈ Map Extensions: Safe map parsing and utility functions
- π Base Data Models: Abstract classes for consistent data handling
- π Interfaces: Logger and connectivity service interfaces
- π‘οΈ Type Safety: Full null safety support with comprehensive type checking
- π§ͺ Comprehensive Testing: 169 tests with complete coverage including edge cases
π¦ Installation #
Add this to your package's pubspec.yaml
file:
dependencies:
flutter_shared_utilities: ^1.0.1
Then run:
flutter pub get
π Quick Start #
import '../../flutter_shared_utilities.dart';
void main() {
// String utilities
String? text = "Hello World";
bool isNullEmpty = text.isNullEmpty; // false
bool startsWith = text.startsWithIgnoreCase("hello"); // true
// Safe JSON parsing with double-encoding prevention
String jsonString = '{"name": "John", "age": 30}';
final parsed = SafeParser.safeDecodeJson(jsonString);
// No double-encoding - already valid JSON preserved
String alreadyEncoded = SafeParser.safeEncodeJson('"hello"');
// β '"hello"' (correct, not "\"hello\"")
// List utilities
List<String> fruits = ['apple', 'banana'];
fruits.addAllIfNotExists(['apple', 'orange']); // Only adds 'orange'
}
π API Reference #
String Extensions #
StringUtilExtensions
Provides utility methods for string manipulation and validation:
String? text = "Hello World";
// Case-insensitive operations
bool equals = text.compareWithoutCase("hello world"); // true
bool startsWith = text.startsWithIgnoreCase("hello"); // true
bool contains = text.containsWithoutCase("world"); // true
// Null/empty checks
bool isNull = text.isNullString; // false
bool isEmpty = text.isNullEmpty; // false
// JSON validation
bool isObject = '{"key": "value"}'.isJsonObject; // true
bool isArray = '[1, 2, 3]'.isJsonArray; // true
bool isPrimitive = '"string"'.isJsonPrimitive; // true
List Extensions #
ListUtilExtensions
Smart list operations with duplicate prevention:
List<String> items = ['apple', 'banana'];
// Insert if not exists
bool inserted = items.insertIfNotExists('apple', index: 0); // false (already exists)
bool inserted2 = items.insertIfNotExists('orange', index: 1); // true
// Add all if not exists
items.addAllIfNotExists(['apple', 'grape', 'banana']); // Only adds 'grape'
// Remove if exists
bool removed = items.removeIfExist('apple'); // true
Safe Parser #
SafeParser
Robust JSON parsing with error handling and intelligent double-encoding prevention:
// Safe JSON encoding - prevents double-encoding
String encoded = SafeParser.safeEncodeJson({'name': 'John', 'age': 30});
// β '{"name":"John","age":30}'
// Already encoded JSON is preserved (no double-encoding)
String alreadyEncoded = SafeParser.safeEncodeJson('"hello"');
// β '"hello"' (NOT "\"hello\"")
String jsonObject = SafeParser.safeEncodeJson('{"existing": "json"}');
// β '{"existing": "json"}' (preserves valid JSON)
// Safe JSON decoding with fallback handling
Object? decoded = SafeParser.safeDecodeJson('{"name": "John", "age": 30}');
// β Map<String, dynamic>
// Handles malformed JSON gracefully
Object? fallback = SafeParser.safeDecodeJson('{invalid json}');
// β '{invalid json}' (returns original string as fallback)
// Round-trip consistency guaranteed
String original = 'Hello, δΈη! π';
String encoded = SafeParser.safeEncodeJson(original);
Object? decoded = SafeParser.safeDecodeJson(encoded);
// original == decoded β
Key Features:
- π‘οΈ Double-encoding prevention - Intelligently detects already-encoded JSON
- π Unicode support - Handles special characters and emojis correctly
- π Round-trip consistency - Encode β Decode operations are symmetric
- π¨ Graceful error handling - Never crashes, provides sensible fallbacks
- π Comprehensive logging - Debug-friendly error reporting
Base Data Model #
BaseDataModel
Abstract class for consistent data model implementation:
class User extends BaseDataModel<User> {
final String name;
final int age;
const User({required this.name, required this.age});
@override
User fromMap(Map<String, dynamic> map) {
return User(
name: map['name'] as String,
age: map['age'] as int,
);
}
@override
Map<String, dynamic> toMap() {
return {
'name': name,
'age': age,
};
}
@override
List<Object?> get props => [name, age];
}
// Usage
final user = User(name: 'John', age: 30);
String json = user.toJson();
User fromJson = user.fromJson(json);
π§ Additional Utilities #
Safe Debug Print #
import '../../utils/safe_debug_print.dart';
safeDebugLog('Debug message', stackTrace: StackTrace.current);
Object Serialization Extensions #
// Safe type conversion
String? value = '123';
int? number = value.fromSerializable<int>(); // 123
double? decimal = value.fromSerializable<double>(); // 123.0
π§ͺ Testing #
The package includes comprehensive tests for all functionality with 169 total tests covering every feature:
Test Coverage #
- β SafeParser Tests (26 tests) - Complete coverage including double-encoding prevention
- β MapParserExtensions Tests (52 tests) - All type conversions and edge cases
- β Serialization Extensions Tests - Complex type handling and validation
- β String Utility Tests - Case-insensitive operations and JSON validation
- β List Utility Tests - Duplicate prevention and smart operations
- β Base Data Model Tests - Model conversion and serialization
Test Quality Standards #
- π‘οΈ Safe Type Checking - No null force operators (
!
) or unsafe casting (as
) - π Bounds Checking - All array access is bounds-checked
- π Unicode Testing - Special characters, emojis, and international text
- π Round-trip Verification - Encode/decode consistency validation
- π¨ Error Handling - Graceful failure and fallback behavior testing
- π Edge Cases - Empty data, null values, malformed inputs, large datasets
Running Tests #
# Run all tests
flutter test
# Run specific test files
flutter test test/utils/safe_parser_test.dart
flutter test test/extensions/map/map_parser_extensions_test.dart
# Run with coverage
flutter test --coverage
Test Results #
169/169 tests passing β
100% test coverage on critical functionality
π€ Contributing #
Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature
) - Commit your changes (
git commit -m 'Add some amazing feature'
) - Push to the branch (
git push origin feature/amazing-feature
) - Open a Pull Request
π License #
This project is licensed under the MIT License - see the LICENSE file for details.
π Issues and Feedback #
Please file issues and feature requests on the GitHub repository.
π Version History #
See CHANGELOG.md for a detailed version history.
π Links #
Made with β€οΈ for the Flutter community