我正在尝试理解 SafeArea Flutter 中的小部件。
SafeArea 代码添加到 Flutter Gallery 应用程序 here在 github 中到处显示 top:false
和 bottom:false
。为什么在这些情况下需要将这些设置为 false?
最佳答案
SafeArea
基本上是一个美化的 Padding
小部件。如果您使用 SafeArea
包装另一个小部件,它会添加任何必要的填充,以防止您的小部件被系统状态栏、槽口、孔、圆角和制造商的其他“创意”功能阻挡。
如果您使用带有 AppBar 的 Scaffold,将在屏幕顶部计算适当的间距,而无需将 Scaffold 包裹在 SafeArea 中,并且状态栏背景将受到 AppBar 颜色的影响(此处为红色)示例)。
如果将 Scaffold 包裹在 SafeArea 中,则状态栏区域将具有黑色背景,而不受 AppBar 影响。
这是一个没有设置 SafeArea
的例子:
Align(
alignment: Alignment.topLeft, // and bottomLeft
child: Text('My Widget: ...'),
)
再次将小部件包装在 SafeArea 小部件中:
Align(
alignment: Alignment.topLeft, // and bottomLeft
child: SafeArea(
child: Text('My Widget: ...'),
),
)
您可以为不受槽口等影响的边缘设置最小填充:
SafeArea(
minimum: const EdgeInsets.all(16.0),
child: Text('My Widget: ...'),
)
您还可以关闭任何一侧的安全区域插入:
SafeArea(
left: false,
top: false,
right: false,
bottom: false,
child: Text('My Widget: ...'),
)
将它们全部设置为 false 与不使用 SafeArea 相同。所有边的默认值为 true
。大多数时候你不需要使用这些设置,但我可以想象这样一种情况,你有一个小部件填满整个屏幕。您希望顶部不被任何东西阻挡,但您不关心底部。在这种情况下,您只需设置 bottom: false
而将其他边保留为默认的 true
值。
SafeArea(
bottom: false,
child: myWidgetThatFillsTheScreen,
)
如果你想玩更多,这里是 main.dart:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
body: BodyWidget(),
),
);
}
}
class BodyWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Align(
alignment: Alignment.topLeft,
child: SafeArea(
left: true,
top: true,
right: true,
bottom: true,
minimum: const EdgeInsets.all(16.0),
child: Text(
'My Widget: This is my widget. It has some content that I don\'t want '
'blocked by certain manufacturers who add notches, holes, and round corners.'),
),
);
}
}
https://stackoverflow.com/questions/49227667/