【问题标题】:How to have two different background colors for a container如何为容器设置两种不同的背景颜色
【发布时间】:2020-08-16 10:21:32
【问题描述】:

我希望容器看起来像这样:

backGround colorred 取决于设备的电池电量。我希望它是动态的。

我是这样尝试的:

return Container(
      child: Row(
        children: [
          Expanded(flex: 100-battery,child: SizedBox()),
          Expanded(flex: battery,child: Container(child: Text(battery.toString()+'%', style: TextStyle(fontSize: 10,),),color: Colors.green)),
        ],
      ),
      decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(5), border: Border.all(color: Colors.white)),
    );

看起来不错,问题是Text 与一侧对齐。我希望它在一侧。所以我必须指定两个background color 来解决这个问题。有什么想法吗?

【问题讨论】:

    标签: flutter dart colors containers


    【解决方案1】:

    使用BoxDecorationgradient参数

    您可以使用三种渐变中的一种

    • 线性渐变
    • 径向渐变
    • SweepGradient

    以此为例

     Container(
          decoration: BoxDecoration(
            gradient: RadialGradient(
              center: Alignment.center,
              colors: [const Color(0xFF283250), const Color(0xFF0C1225)],
              tileMode: TileMode.clamp,
            ),
            borderRadius: BorderRadius.circular(5),
            border: Border.all(color: Colors.white),
          ),
          child: Container(
            alignment: Alignment.center,
            child: Row(
              children: [
                Expanded(flex: 100 - battery, child: SizedBox()),
                Expanded(
                    flex: battery,
                    child: Container(
                        child: Text(
                          battery.toString() + '%',
                          style: TextStyle(
                            fontSize: 10,
                          ),
                        ),
                        color: Colors.green)),
              ],
            ),
          ),
        ),
    

    https://api.flutter.dev/flutter/painting/Gradient-class.html了解有关使用gradients的更多信息

    【讨论】:

    • 有没有办法让它更清楚一点?现在模糊了@Kherel
    【解决方案2】:

    我做得更好:

    decoration: BoxDecoration(
            gradient: LinearGradient(
              begin: Alignment.centerLeft,//Starting point
              end: Alignment.centerRight,//Ending point
              stops: [0.5, 0], //First Part is the amount of space the first color has 
              //occupy and the second parameter is the space that is to be occupied by
              //mixture of both colors.
            colors: [Colors.green, Colors.amber], // List of colors
            ),
    

    【讨论】:

      猜你喜欢
      • 2016-01-30
      • 2021-11-14
      • 2014-11-15
      • 2021-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-23
      相关资源
      最近更新 更多