如何为容器使用两种不同的背景色

问题描述

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

battery

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

我这样尝试过:

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解决此问题。有想法吗?

解决方法

使用gradient的{​​{1}}参数

您可以使用三个渐变之一

  • 线性渐变
  • RadialGradient
  • SweepGradient

以这个为例

BoxDecoration

https://api.flutter.dev/flutter/painting/Gradient-class.html中了解有关使用 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)),],的更多信息

,

我做得更好:

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
        ),