如何实现Flutter中Container响应式 解决Stack下组件尺寸不随屏幕适配问题
问题原因
- 按屏幕总宽度比例计算元素尺寸、位置的逻辑没有扣除左侧固定尺寸图片、全局边距的占位,不同屏幕宽度下偏移误差会被放大
- 右侧价格列使用
left: width * 0.85绝对定位,小屏会超出容器边界,大屏会和中间文本区域留白过大 - 中间文本区域固定设置
width: width * 0.6,无法自适应填充左侧图片到右侧价格之间的剩余空间
修复思路
- 中间文本区域外层套
Expanded组件,自动占满Row中除固定宽图片外的剩余宽度,删除固定宽度配置 - 右侧价格的
Positioned组件改用right属性而非left属性相对容器右边缘对齐,避免不同屏幕尺寸下的位置偏移
修复后完整代码
class MyHomePage extends StatelessWidget { const MyHomePage({Key? key}) : super(key: key); @override Widget build(BuildContext context) { var width = MediaQuery.of(context).size.width; return Center( child: Container( height: 135, width: width, decoration: BoxDecoration( border: Border.all(color: Colors.yellow), color: Colors.white, borderRadius: BorderRadius.circular(20), ), child: Stack( children: <Widget>[ Container( child: Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ Padding( padding: const EdgeInsets.all(8.0), child: ClipRRect( borderRadius: BorderRadius.circular(10), child: Image.network( 'https://images3.alphacoders.com/823/82317.jpg', fit: BoxFit.cover, height: 120, width: 120, ), ), ), // 新增Expanded组件自动填充剩余宽度 Expanded( child: Padding( padding: const EdgeInsets.fromLTRB(0, 15, 50, 0), // 右侧预留价格列的空间避免重叠 child: Container( height: 110, child: const Text( 'product.name', textAlign: TextAlign.justify, style: TextStyle(fontSize: 17), ), ), ), ), ], ), ), Positioned( top: 80, right: 15, // 改用right相对右边缘对齐,替换原来的left配置 child: Column( children: const [ Text( 'Rs200', style: TextStyle(fontSize: 17, fontWeight: FontWeight.bold), ), Text( 'Rs300', style: TextStyle( decoration: TextDecoration.lineThrough, fontSize: 17, color: Colors.blueGrey), ), ], ), ), ], )), ); } }
效果截图


内容的提问来源于stack exchange,提问作者Nitish Garg
相关产品推荐
相关产品推荐

