Flutter SafeArea 的使用

10 min read

Android 和 IOS都有状态栏,甚至IOS还有叫做“HomeIndicator”的横条。所以一不留神就会出现适配问题。

Flutter中常使用的BottomNavigationBarAppBar 其实就在内部处理了此类问题

class _AppBarState extends State<AppBar> {

  @override
  Widget build(BuildContext context) {
    
    if (widget.primary) {
      appBar = SafeArea(  // <--- 1
        top: true,
        child: appBar,
      );
    }

    return Semantics(
      container: true,
      child: AnnotatedRegion<SystemUiOverlayStyle>(
        value: overlayStyle,
        child: Material( // <--- 2
          color: widget.backgroundColor
            ?? appBarTheme.color
            ?? themeData.primaryColor,
          child: Semantics(
            explicitChildNodes: true,
            child: appBar,
          ),
        ),
      ),
    );
  }
}

使用

Material( // 需要颜色填充到边界区域可以使用
  color: Colors.white,
  child: SafeArea(
    child: Container(),
  ),
)