本文介绍了Flutter-使用SafeArea的系统栏颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为带有彩色系统栏的flutter应用程序添加 SafeArea 小部件,但不知何故它们始终会变黑.

I am trying to add SafeArea widget for the flutter app with colorized system bars but somehow they are always turning black.

  @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 包裹在 color 属性设置为白色的 Container 内,则可以使用,但是系统栏图标也变为白色

If I wrap SafeArea inside a Container with color property set to white, it works but system bar icons also turn white

推荐答案

在@ david-carrilho的答案的基础上,我创建了这个简单的小部件

Building on @david-carrilho's answer, I created this simple widget

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,
      ),
    );
  }
}

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

Then wherever I would use a SafeArea, I use my little wrapper widget 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 会根据设备简单地添加必要的填充.

The reason why this works is because it creates a container behind your content with the specified color, then SafeArea simply adds the necessary padding based on the device.

这篇关于Flutter-使用SafeArea的系统栏颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-26 22:12