Flutter Web如何适配Windows系统缩放调整文字与容器尺寸
Flutter Web Windows系统缩放适配方案
- 替换固定尺寸为相对单位
硬编码固定数值是适配异常的核心原因,Flutter逻辑像素会跟随系统DPI缩放比例动态变化,固定值会导致高缩放比例下元素溢出、挤压变形。可通过两种方式实现尺寸自适应:- 原生MediaQuery实现
以设计稿基准尺寸为参照,按当前屏幕宽度比例换算实际尺寸:
// 全局工具方法,设计稿基准宽度可替换为你的实际开发参考值(如1920) double adaptWidth(BuildContext context, double designWidth) { return MediaQuery.of(context).size.width * designWidth / 1920; } // 容器使用示例 Container( width: adaptWidth(context, 200), // 设计稿上200px宽度自动适配当前屏幕 height: adaptWidth(context, 100), margin: EdgeInsets.symmetric(horizontal: adaptWidth(context, 16)), )- 第三方适配包flutter_screenutil实现
引入依赖后初始化即可直接使用封装好的适配单位:
// 主入口初始化配置 return ScreenUtilInit( designSize: const Size(1920, 1080), // 填写你的设计稿基准尺寸 minTextAdapt: true, builder: (context, child) => MaterialApp( // 你的原有应用配置 ), ); // 元素使用示例 Container( width: 200.w, // 自适应宽度 height: 100.h, // 自适应高度 padding: EdgeInsets.all(8.r), // 自适应边距/圆角 ) - 原生MediaQuery实现
- 字体自适应调整
你的现有字体配置可做如下修改实现跟随系统缩放动态调整:
若使用flutter_screenutil,可直接用ThemeData.dark().copyWith( scaffoldBackgroundColor: bgColor, textTheme: GoogleFonts.poppinsTextTheme(Theme.of(context).textTheme) .apply( bodyColor: Colors.white, fontSizeFactor: MediaQuery.of(context).textScaleFactor, ), canvasColor: secondaryColor, )sp单位定义字体大小:Text( "展示文本", style: TextStyle(fontSize: 14.sp), ) - 可选:强制固定缩放比例(不推荐,不符合系统用户操作习惯)
如果你不需要跟随系统缩放,可全局覆盖缩放参数强制固定显示比例:MaterialApp( builder: (context, child) { return MediaQuery( data: MediaQuery.of(context).copyWith( devicePixelRatio: 1.0, textScaleFactor: 1.0, ), child: child!, ); }, )
内容的提问来源于stack exchange,提问作者Thoxh
相关产品推荐
相关产品推荐

