API for encoding/decoding a money value enables an application to store values in a database or send over a network.
A money value can be encoded to any type. For example it can be coded as a string in the format like 'USD 5.00'.
Note: this is a trivial example and you would simply use the parse/format methods to encode/decode from/to a string.
Encoding
import 'package:money2/money2.dart';
class MoneyToStringEncoder implements MoneyEncoder<String> {
@override
String encode(MoneyData data) {
// Receives MoneyData DTO and produce
// a string representation of money value...
final major = data.integerPart.toString();
final minor = data.decimalPart.toString();
return '${data.currency.isoCode} $major.${Strings.padRight(minor, 2, '0')}';
}
test('Encoding', () {
final fiveDollars = Money.parse('5.00', isoCode: 'USD');
final encoded = fiveDollars.encodedBy(MoneyToStringEncoder());
// Now we can save `encoded` to database...
expect(encoded, equals('USD 5.00'));
});
Decoding
import 'package:money2/money2.dart';
class StringToMoneyDecoder implements MoneyDecoder<String> {
Currencies _currencies;
StringToMoneyDecoder(this._currencies) {
if (_currencies == null) {
throw ArgumentError.notNull('currencies');
}
}
/// Returns decoded `MoneyData` or throws a `FormatException`.
MoneyData decode(String encoded) {
// If `encoded` has an invalid format throws FormatException;
// Extracts currency code from `encoded`:
final currencyCode = ...;
// Tries to find information about a currency:
final currency = _currencies.find(currencyCode);
if (currency == null) {
throw FormatException('Unknown currency: $currencyCode.');
}
// Using `currency.precision`, extracts minorUnits from `encoded`:
final minorUnits = ...;
return MoneyData.from(minorUnits, currency);
}
}
import 'money2.dart';
try {
final value = Money.decoding('USD 5.00', MyMoneyDecoder(myCurrencies));
// ...
} on FormatException {
// ...
}