简体   繁体   English

如何在 Flutter 容器中设置背景颜色

[英]How do I set background color in a Flutter container

I have a container widget that I can't get to show a background color.我有一个无法显示背景颜色的容器小部件。 This widget is the first in a Column so the width is the full screen.这个小部件是列中的第一个,因此宽度是全屏。 I should be able to see the background to the right of the button.我应该能够看到按钮右侧的背景。

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

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 100,
      color: Colors.green, // <---------------- NOT WORKING
      child: ElevatedButton(
        onPressed: () => null,
        child: Text('Home'),
      ),
    );
  }
}

Here's a link to a dartpad example: https://dartpad.dev/fc5fdd6c227747abe039d73a07d00a54这是 dartpad 示例的链接: https://dartpad.dev/fc5fdd6c227747abe039d73a07d00a54

Thats happens due to ElevatedButton, try to change it to TextButton.这是由于 ElevatedButton 而发生的,请尝试将其更改为 TextButton。

ElevatedButton's primary color hides the Container's green color. ElevatedButton 的原色隐藏了 Container 的绿色。 You can use style property of ElevatedButton and assign Colors.green like this:您可以使用ElevatedButtonstyle属性并像这样分配Colors.green

return Container(
  height: 100,
  child: ElevatedButton(
    style: ElevatedButton.styleFrom(
      primary: Colors.green
    ),
    onPressed: () => null,
    child: Text('Home'),
  ),
);

Both answers above lead me to the solution.上面的两个答案都让我找到了解决方案。

For anyone else wanted to do something like this, putting a DecoratedBox fixed it.对于其他想要做这样的事情的人,放置一个 DecoratedBox 来修复它。

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 48,
      child: DecoratedBox(
        decoration: const BoxDecoration(color: Colors.red),
        child: Row(mainAxisAlignment: MainAxisAlignment.start, children: [
          ElevatedButton(
            onPressed: () => null,
            child: Text('Next'),
          ),
        ]),
      ),
    );
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM