Flutter 响应式 UI:平板 / 折叠屏 / 桌面适配
Flutter 一份代码六端跑(iOS / Android / Web / Windows / macOS / Linux),但默认布局只针对手机。要在大屏 / 折叠屏上看着舒服,需要主动适配。
一、核心思路:Adaptive vs Responsive
| 概念 | 含义 |
|---|---|
| Responsive(响应式) | 同一布局根据宽度伸缩(Web 网页常见) |
| Adaptive(自适应) | 不同布局针对不同设备(手机底导航 vs 桌面侧边栏) |
实战通常两者结合:小变化用 Responsive,结构性变化用 Adaptive。
二、查询屏幕信息:MediaQuery
final media = MediaQuery.of(context);
media.size.width // 屏幕宽
media.size.height // 屏幕高
media.devicePixelRatio // 像素密度
media.padding // 安全区(刘海、底部 home 条)
media.viewInsets // 键盘等遮挡
media.orientation // 横屏 / 竖屏
media.platformBrightness // 系统亮 / 暗常用便捷:
final width = MediaQuery.sizeOf(context).width; // 仅订阅 size
final padding = MediaQuery.paddingOf(context);sizeOf 比 of 更精细,只在 size 变化时重建(回顾 05 的细粒度订阅)。
三、LayoutBuilder:拿父级约束
MediaQuery 是屏幕级,LayoutBuilder 是当前 Widget 父级给的最大尺寸:
LayoutBuilder(builder: (_, constraints) {
if (constraints.maxWidth > 600) return TabletLayout();
return PhoneLayout();
})适合"组件内部根据可用空间调整"。
四、Material 3 的 Window Size Class
Material 3 给了一套断点(breakpoint)规范:
| 类型 | 宽度 | 典型设备 |
|---|---|---|
| Compact | < 600 | 手机竖屏 |
| Medium | 600~840 | 折叠屏展开 / 平板竖屏 |
| Expanded | 840~1200 | 平板横屏 / 小桌面 |
| Large | 1200~1600 | 桌面 |
| ExtraLarge | > 1600 | 大显示器 |
WindowSizeClass _windowSize(double w) {
if (w < 600) return WindowSizeClass.compact;
if (w < 840) return WindowSizeClass.medium;
if (w < 1200) return WindowSizeClass.expanded;
if (w < 1600) return WindowSizeClass.large;
return WindowSizeClass.extraLarge;
}或用包 flutter_adaptive_scaffold(官方实验包),帮你按规范布局。
五、典型自适应模式
1. 底导航 → 侧边栏 → 抽屉
class HomeScaffold extends StatelessWidget {
final Widget body;
const HomeScaffold({required this.body, super.key});
@override
Widget build(BuildContext context) {
final width = MediaQuery.sizeOf(context).width;
if (width < 600) {
// 手机:底部导航
return Scaffold(
body: body,
bottomNavigationBar: NavigationBar(...),
);
} else if (width < 1200) {
// 平板:NavigationRail
return Scaffold(
body: Row(
children: [
NavigationRail(...),
const VerticalDivider(width: 1),
Expanded(child: body),
],
),
);
} else {
// 桌面:常驻 Drawer
return Scaffold(
body: Row(
children: [
const SizedBox(width: 256, child: ExtendedDrawer()),
Expanded(child: body),
],
),
);
}
}
}2. Master-Detail(列表 + 详情)
手机:点击列表跳详情页 平板 / 桌面:左右分栏
class MasterDetail extends StatelessWidget {
@override
Widget build(BuildContext context) {
final wide = MediaQuery.sizeOf(context).width >= 720;
if (wide) {
return Row(
children: [
SizedBox(width: 320, child: TodoList()),
const VerticalDivider(width: 1),
Expanded(child: TodoDetail()),
],
);
}
return TodoList(onTap: (id) => Navigator.push(
context,
MaterialPageRoute(builder: (_) => TodoDetail(id: id)),
));
}
}3. 内容最大宽度限制
桌面屏幕宽,文字横通屏看着累。包一个 ConstrainedBox:
Center(
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 720),
child: Article(),
),
)六、Flex 布局响应式
Row(
children: [
Flexible(flex: 2, child: Sidebar()),
Flexible(flex: 5, child: Content()),
if (wide) Flexible(flex: 3, child: Aside()),
],
)Wrap 自动换行:
Wrap(
spacing: 8,
runSpacing: 8,
children: tags.map((t) => Chip(label: Text(t))).toList(),
)七、Grid:列数跟随宽度
GridView.builder(
gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent: 200, // 每个 item 最大 200,自动算列数
childAspectRatio: 0.75,
mainAxisSpacing: 8,
crossAxisSpacing: 8,
),
itemCount: items.length,
itemBuilder: ...
)maxCrossAxisExtent:item 最大宽度,屏幕宽 → 列多;窄 → 列少。
八、折叠屏适配
折叠屏(三星 Fold、Pixel Fold)有"折痕"和"展开/折叠"两种状态。
DisplayFeature
final features = MediaQuery.of(context).displayFeatures;
for (final f in features) {
if (f.type == DisplayFeatureType.hinge) {
// 折痕在 f.bounds 区域,避开它
}
}TwoPane
dual_screen 包(社区)简化双屏布局:
dependencies:
dual_screen: ^1.0.4TwoPane(
pane1: TodoList(),
pane2: TodoDetail(),
panePriority: TwoPanePriority.both, // 折叠时只显 pane1
)折叠时显示一个 pane,展开时双 pane,自动适配。
九、字体 / 间距适配
1. 设计稿映射:flutter_screenutil
设计稿 375x812,代码里直接写设计稿数值:
dependencies:
flutter_screenutil: ^5.9.3ScreenUtilInit(
designSize: const Size(375, 812),
builder: (_, __) => MaterialApp(...),
)
// 用
Container(width: 100.w, height: 50.h);
Text('hi', style: TextStyle(fontSize: 14.sp));但 screenutil 在大屏(平板 / 桌面)会字体超大,需要按 windowSize 设上限:
designSize: width < 600 ? const Size(375, 812) : const Size(600, 800),或干脆只在手机用 screenutil,平板手写。
2. textScaleFactor
系统级"字体大小"用户可设。Flutter 自动应用,但要保证布局不爆:
MediaQuery(
data: MediaQuery.of(context).copyWith(
textScaler: TextScaler.linear(1.0), // 无视系统设置
),
child: SomeFixedLayout(),
)通常不要写死,尊重用户设置;但表格、状态栏等空间紧张的可以限制。
十、桌面 / Web 特有交互
1. 鼠标 hover
MouseRegion(
onEnter: (_) => setState(() => hover = true),
onExit: (_) => setState(() => hover = false),
child: AnimatedContainer(...),
)
// 或直接用 InkWell.hoverColor2. 鼠标右键
GestureDetector(
onSecondaryTapDown: (d) => showContextMenu(d.globalPosition),
child: ...,
)3. 键盘快捷键
Shortcuts(
shortcuts: const {
SingleActivator(LogicalKeyboardKey.keyS, control: true): SaveIntent(),
},
child: Actions(
actions: {SaveIntent: CallbackAction(onInvoke: (_) => save())},
child: Focus(autofocus: true, child: Editor()),
),
)Shortcuts + Actions 是 Flutter 的命令模式,适合复杂快捷键。
4. 拖拽文件入窗
desktop_drop 包接收拖入文件:
DropTarget(
onDragDone: (detail) {
for (final f in detail.files) print(f.path);
},
child: ...,
)十一、滚动条:桌面要可拖
桌面用户期望看到滚动条,Flutter 默认手机风格(滚动时才出现):
Scrollbar(
thumbVisibility: true, // 始终显示
child: ListView(...),
)或全局:
ScrollBehavior(
// 自定义所有滚动行为
)十二、Cupertino 自适应
iOS 用户期望 iOS 风格:
import 'package:flutter/cupertino.dart';
Platform.isIOS
? CupertinoButton(...)
: ElevatedButton(...)或 flutter_platform_widgets 一行写两端:
PlatformElevatedButton(child: Text('OK'), onPressed: () {})iOS 自动 CupertinoButton,Android 自动 ElevatedButton。
十三、安全区与底部 inset
刘海、底部 home 条、键盘:
// 自动避开
SafeArea(
child: ...,
)
// 自动避开键盘
Scaffold(
resizeToAvoidBottomInset: true, // 默认 true
body: ...,
)
// 手动拿
final insets = MediaQuery.of(context).viewInsets.bottom; // 键盘高度
final padding = MediaQuery.of(context).padding.top; // 状态栏 / 刘海十四、横屏适配
final orientation = MediaQuery.orientationOf(context);
if (orientation == Orientation.landscape) {
return Row(children: [Sidebar(), Expanded(child: Body())]);
}
return Column(children: [Header(), Expanded(child: Body())]);锁定方向(只允许竖屏):
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
]);十五、完整自适应 Scaffold
社区方案 flutter_adaptive_scaffold(Material 推荐):
dependencies:
flutter_adaptive_scaffold: ^0.2.7AdaptiveScaffold(
selectedIndex: _idx,
onSelectedIndexChange: (i) => setState(() => _idx = i),
destinations: const [
NavigationDestination(icon: Icon(Icons.home), label: '首页'),
NavigationDestination(icon: Icon(Icons.search), label: '搜索'),
NavigationDestination(icon: Icon(Icons.person), label: '我的'),
],
body: (_) => HomeBody(),
smallBody: (_) => MobileHomeBody(), // 可单独定制小屏
)它自动:
- 手机 → 底导航
- 平板 → NavigationRail
- 桌面 → 扩展抽屉
十六、调试技巧
1. 设备预览
device_preview 包,在 Web / 桌面调试时模拟各种设备:
dev_dependencies:
device_preview: ^1.2.0DevicePreview(
builder: (_) => MyApp(),
)切换 iPhone / iPad / Pixel 等,UI 即时变化。
2. 在 IDE 切换尺寸
VS Code 装 Flutter 插件,调试时面板可改 size。
3. 真机测
真机 / 真平板才靠谱。模拟器只能粗看。
十七、常见坑
1. 写死宽高
SizedBox(width: 375, ...) // ❌ 平板上太挤→ 用 Expanded、Flexible、约束(ConstrainedBox)。
2. 字体在大屏巨大
screenutil.sp 按比例放大,平板上 14sp 可能变成 30+。要么限制 designSize,要么平板用 fontSize 直接写。
3. 横屏键盘弹起内容被压
Scaffold.resizeToAvoidBottomInset = false 关掉自动调整,手动用 SingleChildScrollView 包裹表单。
4. 桌面没有手势,只有鼠标
GestureDetector(onLongPress: ...) // ⚠️ 桌面没人长按→ 桌面用 onSecondaryTapDown(右键)。
5. iPad 默认上下分屏不支持
需要在 Info.plist 加配置:
<key>UISupportsDocumentBrowser</key>
<true/>
<key>UIRequiresFullScreen</key>
<false/>6. Scaffold 外用 BottomNavigationBar
→ 报错。BottomNavigationBar 必须在 Scaffold 内。
十八、推荐组合
小项目 :MediaQuery + LayoutBuilder 手写
中型 App :flutter_adaptive_scaffold + screenutil(只手机)
桌面 / Web :NavigationRail + Master-Detail + 鼠标交互
全平台 :三种布局 + Cupertino 风格识别十九、和已学知识的串联
- Theme(17)的
colorScheme跨设备一致 - 路由(12)的
StatefulShellRoute可以在桌面 / 平板自动表现为侧栏 - 性能(18):大屏不要 ListView 加载所有,继续用 builder
- 平板的 Master-Detail 配合 Riverpod 的 family Provider(09):右侧详情根据左侧选中的 id 加载
二十、心智模型
< 600 手机 → 底导航 + 单栏
600~840 小平板 → NavigationRail + 单栏 / 双栏
840+ 大平板 → 双栏 Master-Detail
1200+ 桌面 → 三栏 + 鼠标交互 + 快捷键核心:让 UI 跟内容,而不是设备。检查"这块在 800px 看着挤吗?"比"这是不是平板?"更稳。
写出真正能在多设备跑的 Flutter UI 不复杂,但要从一开始就想着——后期重构成本高得多。