Flutter适配求助:不同屏幕下字体大小及应用界面调整方法
Flutter 屏幕尺寸适配方案(含Device Pixel Ratio相关方法)
一、基于Device Pixel Ratio的基础适配公式
核心逻辑是将设计稿尺寸按设备像素密度比例缩放,公式为:
缩放后的尺寸 = 设计稿尺寸 × (当前设备实际像素宽度/高度 ÷ 设计稿基准像素宽度/高度)
假设你的设计稿以iPhone 6/7/8为基准(逻辑尺寸375×667,对应实际像素750×1334,像素密度2.0),可以用以下代码实现:
// 定义设计稿基准尺寸 const double designBaseWidth = 375; const double designBaseHeight = 667; // 获取适配后的宽度 double adaptWidth(BuildContext context, double designWidth) { final mediaQuery = MediaQuery.of(context); final double actualScreenWidth = mediaQuery.size.width * mediaQuery.devicePixelRatio; return designWidth * (actualScreenWidth / designBaseWidth); } // 获取适配后的高度 double adaptHeight(BuildContext context, double designHeight) { final mediaQuery = MediaQuery.of(context); final double actualScreenHeight = mediaQuery.size.height * mediaQuery.devicePixelRatio; return designHeight * (actualScreenHeight / designBaseHeight); }
二、全局封装适配工具类
为了避免重复调用MediaQuery,可以封装一个全局工具类,简化使用:
class ScreenAdapter { static late MediaQueryData _mediaData; static late double _actualScreenWidth; static late double _actualScreenHeight; // 设计稿基准尺寸(根据你的设计稿修改) static const double _designWidth = 375; static const double _designHeight = 667; // 初始化,建议在入口Widget的initState中调用 static void init(BuildContext context) { _mediaData = MediaQuery.of(context); _actualScreenWidth = _mediaData.size.width * _mediaData.devicePixelRatio; _actualScreenHeight = _mediaData.size.height * _mediaData.devicePixelRatio; } // 适配宽度 static double width(double designValue) { return designValue * (_actualScreenWidth / _designWidth); } // 适配高度 static double height(double designValue) { return designValue * (_actualScreenHeight / _designHeight); } // 单独适配字体,避免极端屏幕下字体变形 static double font(double designFontSize) { return designFontSize * (_actualScreenWidth / _designWidth); } }
使用示例:
// 在入口页面初始化 @override void initState() { super.initState(); ScreenAdapter.init(context); } // 布局中直接调用 Container( width: ScreenAdapter.width(100), height: ScreenAdapter.height(50), child: Text('适配文本', style: TextStyle(fontSize: ScreenAdapter.font(16))), )
三、关键注意事项
- 对于固定比例的组件(如圆形头像、卡片),只需适配宽或高其中一个,保持比例一致即可
- 字体适配建议单独处理,避免在大屏设备上字体过大影响布局
- 不要过度依赖设备像素密度,部分折叠屏、平板设备的像素密度特殊,结合实际屏幕像素尺寸判断更稳妥
内容的提问来源于stack exchange,提问作者Nikko Capiroso
相关产品推荐
相关产品推荐

