Money encoding/decoding
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

1
import 'package:money2/money2.dart';
2
class MoneyToStringEncoder implements MoneyEncoder<String> {
3
String encode(MoneyData data) {
4
// Receives MoneyData DTO and produce
5
// a string representation of money value...
6
String major = data.getMajorUnits().toString();
7
String mainor = data.getMinorUnits().toString();
8
​
9
return data.currency.code + ' ' + major + '.' + minor;
10
}
11
}
12
​
13
​
14
final encoded = fiveDollars.encodedBy(MoneyToStringEncoder());
15
// Now we can save `encoded` to database...
Copied!

Decoding

1
import 'package:money2/money2.dart';
2
class StringToMoneyDecoder implements MoneyDecoder<String> {
3
​
4
Currencies _currencies;
5
​
6
StringToMoneyDecoder(this._currencies) {
7
if (_currencies == null) {
8
throw ArgumentError.notNull('currencies');
9
}
10
}
11
​
12
/// Returns decoded `MoneyData` or throws a `FormatException`.
13
MoneyData decode(String encoded) {
14
// If `encoded` has an invalid format throws FormatException;
15
​
16
// Extracts currency code from `encoded`:
17
final currencyCode = ...;
18
​
19
// Tries to find information about a currency:
20
final currency = _currencies.find(currencyCode);
21
if (currency == null) {
22
throw FormatException('Unknown currency: $currencyCode.');
23
}
24
​
25
// Using `currency.precision`, extracts minorUnits from `encoded`:
26
final minorUnits = ...;
27
​
28
return MoneyData.from(minorUnits, currency);
29
}
30
}
Copied!
1
import 'money2.dart';
2
try {
3
final value = Money.decoding('USD 5.00', MyMoneyDecoder(myCurrencies));
4
​
5
// ...
6
} on FormatException {
7
// ...
8
}
Copied!
Last modified 5mo ago
Copy link
Contents