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';classMoneyToStringEncoderimplementsMoneyEncoder<String> {Stringencode(MoneyData data) {// Receives MoneyData DTO and produce// a string representation of money value...String major = data.getMajorUnits().toString();String mainor = data.getMinorUnits().toString();return data.currency.code +' '+ major +'.'+ minor; }}final encoded = fiveDollars.encodedBy(MoneyToStringEncoder());// Now we can save `encoded` to database...
Decoding
import'package:money2/money2.dart';classStringToMoneyDecoderimplementsMoneyDecoder<String> {Currencies _currencies;StringToMoneyDecoder(this._currencies) {if (_currencies ==null) {throwArgumentError.notNull('currencies'); } }/// Returns decoded `MoneyData` or throws a `FormatException`.MoneyDatadecode(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) {throwFormatException('Unknown currency: $currencyCode.'); }// Using `currency.precision`, extracts minorUnits from `encoded`:final minorUnits = ...;returnMoneyData.from(minorUnits, currency); }}
import'money2.dart';try {final value =Money.decoding('USD 5.00', MyMoneyDecoder(myCurrencies));// ...} onFormatException {// ...}