type_caster 0.0.2-alpha 
type_caster: ^0.0.2-alpha copied to clipboard
A powerful type casting and conversion library for Dart that provides safe and flexible type conversion utilities.
Type Caster #
A powerful type casting and conversion library for Dart that provides safe and flexible type conversion utilities.
Features #
- Safe type casting with clear error handling
 - Support for common Dart types (int, double, String, bool, List, Map, etc.)
 - Extensible architecture for custom type converters
 - Null safety support
 - Clear and descriptive error messages
 - No external dependencies
 
Installation #
Add type_caster to your pubspec.yaml:
dependencies:
  type_caster: ^1.0.0
Then run:
flutter pub get
# or
# dart pub get
Usage #
Basic Usage #
import 'package:type_caster/type_caster.dart';
void main() {
  // Safe type casting
  final dynamic value = '123';
  
  // Cast to int
  final int? number = value.castTo<int>();
  print(number); // 123
  
  // With default value
  final double doubleValue = value.castTo<double>(orDefault: 0.0);
  print(doubleValue); // 123.0
  
  // Handle errors
  try {
    final bool boolValue = value.castTo<bool>();
  } on TypeCastException catch (e) {
    print('Failed to cast: ${e.message}');
  }
}
Advanced Usage #
// Custom type conversion
class User {
  final String name;
  final int age;
  
  User({required this.name, required this.age});
  
  factory User.fromJson(Map<String, dynamic> json) {
    return User(
      name: json['name'].castTo<String>(),
      age: json['age'].castTo<int>(),
    );
  }
}
void main() {
  final data = {
    'name': 'John Doe',
    'age': 30,
  };
  
  final user = User.fromJson(data);
  print('${user.name} is ${user.age} years old');
}
API Reference #
Extension Methods #
T? castTo<T>({T? orDefault}): Attempts to cast the value to type TT asType<T>(): Alias forcastTo<T>()T castOrThrow<T>(): Casts the value to type T or throws aTypeCastException
Contributing #
Contributions are welcome! Please feel free to submit a Pull Request.
License #
This project is licensed under the MIT License - see the LICENSE file for details.
Support #
If you find this package useful, please consider giving it a star on GitHub.
For issues and feature requests, please use the issue tracker.