将两种不同的颜色设置为单个容器

Cod*_*ter 3 dart flutter flutter-layout

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

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

die*_*per 6

您可以使用它来完成它,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,
              ),
            ),
          ],
        ),
      ),
    );
  }
}

Run Code Online (Sandbox Code Playgroud)

用法

Center(
        child: MyCustomContainer(
          progress: 0.7,
          size: 100,
          backgroundColor: Colors.grey,
          progressColor: Colors.red,
        ),
      ),
Run Code Online (Sandbox Code Playgroud)

结果

在此处输入图片说明

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


Hem*_*Raj 5

您可以使用容器和线性渐变轻松实现这一点。将颜色作为渐变传递,并在所需的百分比处定义适当的停止点。

例子:

@override
Widget build(BuildContext context) {
  final Color background = Colors.grey;
  final Color fill = Colors.redAccent;
  final List<Color> gradient = [
    background,
    background,
    fill,
    fill,
  ];
  final double fillPercent = 56.23; // fills 56.23% for container from bottom
  final double fillStop = (100 - fillPercent) / 100;
  final List<double> stops = [0.0, fillStop, fillStop, 1.0];

  return Container(
    child: Icon(Icons.forward),
    decoration: BoxDecoration(
      gradient: LinearGradient(
        colors: gradient,
        stops: stops,
        end: Alignment.bottomCenter,
        begin: Alignment.topCenter,
      ),
    ),
  );
} 
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!