【问题标题】:How to add a specific property to a container using extension in flutter如何在 flutter 中使用扩展将特定属性添加到容器
【发布时间】:2022-12-02 20:39:38
【问题描述】:

I am trying to experiement with flutter\'s extension function . So far i have made a good progress, But stuck in modifying a specific property of container keeping all of its previous properties intact .

Sample Worked in TextStyle

extension Theme on Text {
   Text red() {
    return Text(data!, style: style?.copyWith(color: Colors.red));
   }

   Text bigFont() {
    return Text(
      data!,
      style: style?.copyWith(fontSize: 22),
     );
  }
}

And use as Text(\"Hello\",style:TextStyle()).red().bigFont()

Output:

I want to achieve the same using Container but it doesn\'t have copyWith property.i.e I want to make a roundedCorner and then add linear Gradient to it using two different extensions.

Presently my try:

extension sample on Container {
  Container roundedCorner([Color? color, int? x]) {
    return Container(
        decoration: BoxDecoration(
            border: Border.all(),
            borderRadius: BorderRadius.circular(x?.toDouble() ?? 20)),
        child: this);
  }

  Container addGradient(Color colorStart, Color colorEnd) {
    return Container(
      decoration: BoxDecoration(
          gradient: LinearGradient(colors: [colorStart, colorEnd])),
      child: this,
    );
  }
}

Using it as

Container(child: Text(\"Hello\"))
                .roundedCorner()
                .addGradient(Colors.green, Colors.lightGreen);

Output:

Expected Ouput:

Note: This is happening because of nesting of Bordered container within Gradient container. How to overcome this ?

  • you cannot do that, sorry

标签: flutter extension-methods


【解决方案1】:
猜你喜欢
  • 2016-05-07
  • 2014-09-17
  • 1970-01-01
  • 1970-01-01
  • 2020-11-21
  • 2021-02-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多