toPx function
Converts a rem value
to its pixel (px
) equivalent using the current font size
found on the HtmlDocument.
- If
value
is a String or CssValue:- And
value
already has the correct unit, it will not be converted. - And CssValue.unit is not
'px'
or'rem'
, an error will be thrown unlesspassThroughUnsupportedUnits
istrue
, in which case no conversion will take place.
- And
- If
value
is a num, it will be treated as arem
and converted, unlesstreatNumAsPx
istrue
. - If
value
isnull
,null
will be returned.
Examples (all will output 15px
assuming 1rem == 10px
):
toPx('1.5rem');
toPx(new CssValue(1.5, 'rem'));
toPx(1.5);
toPx(15, treatNumAsPx: true);
toPx(15px);
toPx(new CssValue(15, 'px'));
Related: toRem
Implementation
CssValue? toPx(dynamic value, {bool treatNumAsPx = false, bool passThroughUnsupportedUnits = false}) {
if (value == null) return null;
num pxValueNum;
if (value is num) {
pxValueNum = treatNumAsPx ? value : value * rootFontSize;
} else {
var parsedValue = value is CssValue ? value : CssValue.parse(value);
if (parsedValue?.unit == 'px') {
pxValueNum = parsedValue!.number;
} else if (parsedValue?.unit == 'rem') {
pxValueNum = parsedValue!.number * rootFontSize;
} else {
if (passThroughUnsupportedUnits) return parsedValue;
throw ArgumentError.value(value, 'value', 'must be a rem num or a String px/rem value');
}
}
return CssValue(pxValueNum, 'px');
}