jsoncare_flutter 1.0.0
jsoncare_flutter: ^1.0.0 copied to clipboard
A tolerant JSON-to-Dart model generator and safe parsing helper that prevents runtime crashes caused by API type mismatches.
example/example.dart
import 'package:jsoncare_flutter/json_care.dart';
import 'package:jsoncare_flutter/generator.dart';
Future<void> main() async {
// 1. Using the Safe Parsing Engine (JsonCare)
print('--- Safe Parsing Engine ---');
JsonCare.debug = true; // Enable logs for this example
final dynamic rawApiData = {
'id': '101', // API sent String instead of int
'price': '99.50', // API sent String instead of double
'is_available': 1, // API sent int instead of bool
'created_at': '2023-10-27T10:00:00Z', // ISO8601 String
'tags': null, // API sent null instead of List
'metadata': {'v': '1.0'}, // Map
};
final int id = JsonCare.intVal(rawApiData['id']);
final double price = JsonCare.doubleVal(rawApiData['price']);
final bool available = JsonCare.boolVal(rawApiData['is_available']);
final DateTime createdAt = JsonCare.dateVal(rawApiData['created_at']);
final List<String> tags = JsonCare.list(
rawApiData['tags'],
(e) => JsonCare.string(e),
);
final Map<String, dynamic> meta = JsonCare.map(rawApiData['metadata']);
print('ID: $id (Type: ${id.runtimeType})');
print('Price: $price (Type: ${price.runtimeType})');
print('Available: $available');
print('Created At: $createdAt (Local Time)');
print('Tags: $tags');
print('Meta: $meta');
print('\n--- Programmatic Generation ---');
// 2. Using the Generator programmatically
// (Usually you'd use the CLI: dart run jsoncare_flutter generate ...)
const jsonCode =
'{"name": "JsonCare", "version": 1.0, "active": true, "updated_at": "2023-10-27T15:30:00Z"}';
// This will generate files in lib/models/my_model/
// Note: In a real app, you would run this during development.
await JsonCareGenerator.generateFromJsonCode(
rootClassName: 'MyModel',
jsonCode: jsonCode,
outputDir: 'lib/models',
);
print('Model generation initiated. Check lib/models/my_model/ directory.');
}