parse static method
Parse source
and return its CssValue representation.
Accepts a number optionally followed by a CSS length unit.
If no unit is present, 'px'
is used as the unit instead.
If source
is not a valid CSS value, the onError
callback
is called with source
and an error object, and its return
value is used instead. If no onError
is provided, null
is returned.
Examples of accepted values:
'2px'
'10'
20
'1.25em'
'-15%'
Implementation
static CssValue? parse(dynamic source, {CssValue? Function(dynamic value, dynamic error)? onError}) {
CssValue? handleError(Error error) => onError?.call(source, error);
if (source == null) return handleError(ArgumentError.notNull('value'));
final num number;
final String unit;
if (source is num) {
number = source;
unit = 'px';
} else {
var unitMatch = RegExp(r'(?:rem|em|ex|vh|vw|vmin|vmax|%|px|cm|mm|in|pt|pc|ch)?$').firstMatch(source.toString())!;
final parsedUnit = unitMatch.group(0)!;
unit = parsedUnit.isNotEmpty ? parsedUnit : 'px';
final parsedNumber = double.tryParse(unitMatch.input.substring(0, unitMatch.start));
if (parsedNumber == null) {
return handleError(ArgumentError.value(source, 'value', 'Invalid number/unit for CSS value'));
}
number = parsedNumber;
}
if (!number.isFinite) {
// Rule out -Infinity, Infinity, and NaN.
return handleError(ArgumentError.value(number, 'value', 'Number portion of CSS value ($source) must be finite'));
}
return CssValue(number, unit);
}