Flutter Widget 之 SafeArea

848 阅读1分钟

现今的只能设备已经不能提供给应用程序规整的矩形界面来运行了,消息提示栏总是不断闪出,

而一些圆角或者带凹槽的屏幕,也会让应用程序的布局变得更加复杂

这就是为什么Flutter集成了SafeArea功能了

class SafeArea extends StatelessWidget ( 
/// Create a widget that avoids opearting system interfaces. 
    ... 
) 

它使用MediaQuery来检测屏幕的尺寸使应用程序的大小能与屏幕匹配

@override
Widget build(BuildContext context) {
    final EdgeInsets padding = MediaQuery.of(context);
    // Bottom padding has been consumed - i.e. by the keyboard
    if (data.padding.bottom == 0.0 && data.viewInsets.bottom != 0.0 && maintainBottomViewPadding)  
        padding = padding.copyWith(bottom: data.viewPadding.bottom);
    padding: EdgeInsets.only(  
        left: math.max(left ? padding.left : 0.0, minimum.left),  
        top: math.max(top ? padding.top : 0.0, minimum.top),  
        right: math.max(right ? padding.right : 0.0, minimum.right),  
        bottom: math.max(bottom ? padding.bottom : 0.0, minimum.bottom),
    ),child: MediaQuery.removePadding(
        context: context,    
        removeLeft: left,    
        removeTop: top,    
        removeRight: right,    
        removeBottom: bottom,    
        child: child,  
    ),
   );

}

如果你的App看起来是这样的

ListView(
    children: List.generate(
        100,
        (i) => Text('This is some text'),
    )
)

只要使用SafeArea进行封装

 SafeArea(   
    child:ListView(
        children: List.generate(
            100,
            (i) => Text('This is some text'),
        )
    )
)

无论是在iOS环境,还是Android环境它都能保证应用内容正常显示

你甚至可以指定特定的显示区域

SafeArea(
    child: ListView(),
    top: true,
    bottom: true,
    left: false,
    right: true
)

使用Scaffold来进行封装就能起到很好的效果

@override
Widget build(BuildContext context){
    return Scaffold(
        body: SafeArea(
            child: TonsOfOtherWidgets(),
        ),
    );
}

如果想了解有关SafeArea的内容,或者关于Flutter的其他功能,请访问flutter.io

原文翻译自视频:视频地址