Flutter:如何使Placeholder尺寸与图片保持一致?
解决Placeholder尺寸与图片不一致的问题
问题出在kTransparentImage本身——它是一个1x1的极小透明图片,即便你给FadeInImage设置了宽高,加载前占位阶段这个小图的固有尺寸会干扰布局计算,导致Card被异常撑大。以下是几种可行的解决方法:
方案一:给占位符图片明确设置匹配的尺寸和适配规则
直接将占位符改为带尺寸和fit的Image.memory,和主图片参数保持一致:
return Card( clipBehavior: Clip.antiAlias, child: FadeInImage.memoryNetwork( placeholder: Image.memory( kTransparentImage, width: image.previewWidth.toDouble(), height: image.previewHeight.toDouble(), fit: BoxFit.fitWidth, ), image: image.previewUrl, fit: BoxFit.fitWidth, width: image.previewWidth.toDouble(), height: image.previewHeight.toDouble(), ), );
方案二:用SizedBox固定占位符尺寸
用SizedBox直接锁定占位阶段的容器尺寸,内部放入透明图片:
return Card( clipBehavior: Clip.antiAlias, child: FadeInImage.memoryNetwork( placeholder: SizedBox( width: image.previewWidth.toDouble(), height: image.previewHeight.toDouble(), child: Image.memory(kTransparentImage, fit: BoxFit.fill), ), image: image.previewUrl, fit: BoxFit.fitWidth, width: image.previewWidth.toDouble(), height: image.previewHeight.toDouble(), ), );
方案三:使用空容器作为占位符(无视觉占位需求时)
如果不需要任何占位视觉效果,直接用指定尺寸的SizedBox作为占位符即可:
return Card( clipBehavior: Clip.antiAlias, child: FadeInImage.memoryNetwork( placeholder: SizedBox( width: image.previewWidth.toDouble(), height: image.previewHeight.toDouble(), ), image: image.previewUrl, fit: BoxFit.fitWidth, width: image.previewWidth.toDouble(), height: image.previewHeight.toDouble(), ), );
以上方法都会让占位阶段的容器尺寸和目标图片完全匹配,避免Card被异常撑开。
内容的提问来源于stack exchange,提问作者Тимофей
相关产品推荐
相关产品推荐

