繁体   English   中英

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

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

我有一个无法显示背景颜色的容器小部件。 这个小部件是列中的第一个,因此宽度是全屏。 我应该能够看到按钮右侧的背景。

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

这是 dartpad 示例的链接: https://dartpad.dev/fc5fdd6c227747abe039d73a07d00a54

这是由于 ElevatedButton 而发生的,请尝试将其更改为 TextButton。

ElevatedButton 的原色隐藏了 Container 的绿色。 您可以使用ElevatedButtonstyle属性并像这样分配Colors.green

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

上面的两个答案都让我找到了解决方案。

对于其他想要做这样的事情的人,放置一个 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