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

时间:2019-07-17 05:05:24

标签: flutter dart flutter-layout

我正在尝试通过按钮动态地实现自定义设计。我从具有InkWell的容器设计了此按钮。但是我没有正确的方法,如何根据从我的API收到的值为该按钮设置2种不同的颜色。 供参考的是按钮: enter image description here

在此按钮中,灰色部分是容器的背景色。然后,我在此容器中添加了图片。现在,红色应该随从服务器接收的高度而变化。 但是我没有正确的方法去做。

2 个答案:

答案 0 :(得分:2)

您可以使用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,
        ),
      ),

结果

enter image description here

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

答案 1 :(得分:0)

您可以使用容器和线性渐变轻松实现此目的。以渐变形式传递颜色,并以所需的百分比定义适当的光阑。

示例:

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

希望这会有所帮助!