parseBackgroundImage function
Parses a backgroundImage JSON object into a DecorationImage.
Supports Unlayer backgroundImage schema with url, size (cover/contain/custom),
position (center/top-center/etc), and customPosition.
Implementation
DecorationImage? parseBackgroundImage(dynamic bgImageValue, {bool forceCover = false}) {
if (bgImageValue == null) return null;
final bgImage = bgImageValue as Map<String, dynamic>? ?? {};
final url = bgImage['url'] as String? ?? '';
if (url.isEmpty) return null;
// Map size to BoxFit
BoxFit fit;
if (forceCover) {
fit = BoxFit.cover;
} else {
final size = bgImage['size'] as String? ?? 'cover';
switch (size) {
case 'contain':
fit = BoxFit.contain;
break;
case 'custom':
// customSize: ["100%", "auto"] means fill width, auto height
final customSize = bgImage['customSize'] as List<dynamic>?;
if (customSize != null &&
customSize.length == 2 &&
customSize[0].toString().contains('%') &&
customSize[1].toString() == 'auto') {
fit = BoxFit.fitWidth;
} else {
fit = BoxFit.cover;
}
break;
case 'cover':
default:
fit = BoxFit.cover;
}
}
// Map position to Alignment
final position = bgImage['position'] as String? ?? 'center';
Alignment alignment;
switch (position) {
case 'top-center':
alignment = Alignment.topCenter;
break;
case 'top-left':
alignment = Alignment.topLeft;
break;
case 'top-right':
alignment = Alignment.topRight;
break;
case 'bottom-center':
alignment = Alignment.bottomCenter;
break;
case 'bottom-left':
alignment = Alignment.bottomLeft;
break;
case 'bottom-right':
alignment = Alignment.bottomRight;
break;
case 'center-left':
alignment = Alignment.centerLeft;
break;
case 'center-right':
alignment = Alignment.centerRight;
break;
case 'center':
default:
// Try custom position ["50%", "50%"] → Alignment(0, 0)
final customPos = bgImage['customPosition'] as List<dynamic>?;
if (customPos != null && customPos.length == 2) {
final xPercent = double.tryParse(
customPos[0].toString().replaceAll('%', '')) ??
50;
final yPercent = double.tryParse(
customPos[1].toString().replaceAll('%', '')) ??
50;
// Convert 0-100% to -1..1 range
alignment = Alignment(
(xPercent / 50) - 1,
(yPercent / 50) - 1,
);
} else {
alignment = Alignment.center;
}
}
return DecorationImage(
image: NetworkImage(url),
fit: fit,
alignment: alignment,
);
}