首页 > 解决方案 > 为单个容器设置两种不同的颜色

问题描述

我正在尝试从我的按钮动态实现自定义设计。我用 InkWell 的容器设计了这个按钮。但是我没有得到正确的方法,我可以根据从我的 API 接收到的值来为这个按钮设置 2 种不同的颜色。供参考这里是按钮: 在此处输入图像描述

在此按钮中,灰色部分是容器背景颜色。然后我在这个容器中添加了一个图像。现在红色应该随着从服务器接收到的高度动态变化。但我没有得到正确的方法来做到这一点。

标签: flutterdartflutter-layout

解决方案


您可以使用它来完成,gradient但如果您想创建自己的Container以获得更多自定义,这里有:

class MyCustomContainer extends StatelessWidget {
  final Color backgroundColor;
  final Color progressColor;
  final double progress;
  final double size;

  const MyCustomContainer({
    Key key,
    this.backgroundColor = Colors.grey,
    this.progressColor = Colors.red,
    @required this.progress,
    @required this.size,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ClipRRect(
      borderRadius: BorderRadius.circular(size / 2),
      child: SizedBox(
        height: size,
        width: size,
        child: Stack(
          children: [
            Container(
              color: backgroundColor,
            ),
            Align(
              alignment: Alignment.bottomCenter,
              child: Container(
                height: size * progress,
                color: progressColor,
              ),
            ),
          ],
        ),
      ),
    );
  }
}

用法

Center(
        child: MyCustomContainer(
          progress: 0.7,
          size: 100,
          backgroundColor: Colors.grey,
          progressColor: Colors.red,
        ),
      ),

结果

在此处输入图像描述

当然,您可以自定义该小部件以接收 achild并将其放在中心。


推荐阅读