当页面使用了 Scaffold 的 appBar 与 bottomNavigationBar 的页面不需要额外适配,框架里面已经自动适配了。
但很多页面写的时候不会用到 Scanffold ,这样需要手动适配。
适配不同的手机,关键是顶部和底部留有安全区域。
第一种方案:利用 SafeArea 包裹页面,简单不够灵活。
第二种方案:利用 MediaQuery.of(context).padding 获取屏幕四周 padding ,来手动适配,复杂但灵活。
第一种示例代码:
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: SafeArea(
child: Container(
decoration: BoxDecoration(color: Colors.white),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text("适配"),
Text("适配"),
],
),
),
),
);
}
}
第二种示例代码:
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: HomePage(),
);
}
}
class HomePage extends StatelessWidget{
@override
Widget build(BuildContext context) {
final EdgeInsets padding = MediaQuery.of(context).padding;
return Container(
decoration: BoxDecoration(color: Colors.white),
padding: EdgeInsets.fromLTRB(0, padding.top, 0, padding.bottom),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text("适配"),
Text("适配"),
],
),
);
}
}
在 Android 中适配全面屏,需要在 AndroidManifest.xml 中添加:
<!-- 适配全面屏 -->
<meta-data
android:name="android.max_aspect"
android:value="2.3" />
设置应用支持的最大比例。