flutter如何获取屏幕适配宽度

在Flutter开发中,如何获取屏幕的适配宽度?我使用了MediaQuery.of(context).size.width获取屏幕宽度,但在不同设备上显示效果不一致。是否有更准确的适配方法,或者需要结合其他参数计算?求推荐最佳实践方案。

2 回复

使用MediaQuery.of(context).size.width获取屏幕宽度。
结合LayoutBuilderFractionallySizedBox实现适配。
建议使用flutter_screenutil等第三方库简化适配。

更多关于flutter如何获取屏幕适配宽度的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


在 Flutter 中获取屏幕适配宽度,推荐使用 MediaQuery 来获取屏幕尺寸,并结合 LayoutBuilder 或百分比计算实现适配。以下是具体方法:

1. 使用 MediaQuery 获取屏幕宽度

通过 MediaQuery.of(context).size.width 获取逻辑像素宽度。

double screenWidth = MediaQuery.of(context).size.width;

2. 适配方案示例

方案一:百分比布局

Container(
  width: screenWidth * 0.8, // 占用屏幕宽度的80%
  height: 200,
  color: Colors.blue,
)

方案二:使用 LayoutBuilder(推荐)

动态响应布局变化:

LayoutBuilder(
  builder: (context, constraints) {
    double maxWidth = constraints.maxWidth;
    return Container(
      width: maxWidth > 600 ? 500 : maxWidth * 0.9, // 根据宽度断点适配
      color: Colors.red,
    );
  },
)

方案三:使用 FractionallySizedBox

FractionallySizedBox(
  widthFactor: 0.75, // 75% 屏幕宽度
  child: Container(
    height: 100,
    color: Colors.green,
  ),
)

3. 完整示例

class AdaptiveWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final screenWidth = MediaQuery.of(context).size.width;
    
    return Scaffold(
      body: Center(
        child: Container(
          width: screenWidth * 0.8, // 适配宽度
          height: 200,
          color: Colors.amber,
          child: Text('当前宽度: ${screenWidth.toStringAsFixed(1)}'),
        ),
      ),
    );
  }
}

注意事项:

  1. 单位换算:获取的是逻辑像素,与设备物理像素通过 devicePixelRatio 转换
  2. 上下文安全:确保在 build 方法或有有效 context 时调用
  3. 响应式设计:结合 LayoutBuilderOrientationBuilder 处理横竖屏切换

通过以上方法即可实现基于屏幕宽度的适配布局。

回到顶部