首页 > 解决方案 > Flutter - 使用 SafeArea 的系统栏颜色

问题描述

我正在尝试为SafeArea带有彩色系统栏的颤振应用程序添加小部件,但不知何故它们总是变黑。

  @override
  Widget build(BuildContext context) {
    SystemChrome.setSystemUIOverlayStyle(
      SystemUiOverlayStyle.light.copyWith(
        systemNavigationBarIconBrightness: Brightness.dark,
        systemNavigationBarColor: kSurfaceColor,
        statusBarIconBrightness: Brightness.dark,
        statusBarColor: Colors.red, // Note RED here
      ),
    );

    return SafeArea(
      child: Scaffold(
        backgroundColor: kWhiteColor,
        appBar: _buildAppBar(context), // Title and Avatar are built here
        body: _buildBody(), // This function just returns blank Container for now
        floatingActionButton: _buildFAB(context),
        floatingActionButtonLocation: FloatingActionButtonLocation.endFloat,
      ),
    );
  }

这就是我所看到的 在此处输入图像描述

如果我包裹SafeArea在一个属性设置为白色的内部Containercolor它可以工作,但系统栏图标也会变成白色 在此处输入图像描述

标签: flutter

解决方案


基于@david-carrilho 的回答,我创建了这个简单的小部件

import 'package:flutter/material.dart';

class ColoredSafeArea extends StatelessWidget {
  final Widget child;
  final Color color;

  const ColoredSafeArea({Key key, @required this.child, this.color})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      color: color ?? Theme.of(context).colorScheme.primaryVariant,
      child: SafeArea(
        child: child,
      ),
    );
  }
}

然后无论我在哪里使用 a SafeArea,我都会使用我的小包装小部件ColoredSafeArea

class MyExampleView extends StatelessWidget {
  const MyExampleView({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ColoredSafeArea(
      child: Center(
        child: Text('Nice color bar'),
      ),
    );
  }
}

之所以可行,是因为它会在您的内容后面创建一个具有指定颜色的容器,然后SafeArea根据设备简单地添加必要的填充。


推荐阅读