Home > Net >  how to add a specific property to Widget without wrapping it as a child using extension in flutter
how to add a specific property to Widget without wrapping it as a child using extension in flutter

Time:12-02

I am using extension to give padding to the widget

Extension:

extension Hello on Widget {
    paddingAll(int x) {
       return Container(
         padding: const EdgeInsets.all(x.toDouble()),
         child: this,
       );
 }

Use Case :

Container( child: Text("Hello")).paddingAll(40);

But this evaluates to :

 return Container(
   padding: const EdgeInsets.all(20),
   child: Container(
       child: Text("Hello"),
   ));

What I want is :

return Container(
    padding: const EdgeInsets.all(20),
    child: Text("Hello"),
    );

How to achieve this via extension function? If any further more simplified method ,please suggest the same .

CodePudding user response:

try this

extension Hello on Widget {
  paddingAll(int x) {
  return Padding(
  padding: EdgeInsets.all(x.toDouble()),
    child: this
);
}
}

then you should call like this

Container(color: Colors.red, child:Text("Padding").paddingAll(20))
Container(color: Colors.red, child: Text("Normal")).paddingAll(20)

this is the difference

enter image description here

  • Related