1

Is it possible to have decoration (padding, margin, etc.) fields to be set to an application wide default value for all Container widgets?

I know we could create one instance of BoxDecoration, EdgeInstets, etc., store in a variable and assign only that variable in all Containers like this:

Container(
  margin: _margin,
  padding: _padding,
  decoration: _boxDecoration
)

But this is not what i mean. I mean even without assigning any value. I've tried to extend Container like class MyContainer extends Container { ... } and set the desired default values in the constructor but it didn't work.

1 Answer 1

0

You shouldn't extend the Container. You should extend the StatelessWidget. Flutter is more about composing than inheritance.

You should have something like this:

class MyContainer extends StatelessWidget{
  final EdgeInsets _globalPadding = EdgeInsets.all(4);
  final Widget child;

  MyContainer({Key key, this.child}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: _globalPadding,
      child: child,
    );
  }
}

Then you can use MyContainer in the place of any Container.

1
  • Thanks for this. But how do I get all the properties of Container inside MyContainer? Do I have to manually copy them all into my object in order to expose them? Say I wanted to expose padding on MyContainer. Do I now need to go in and manually add padding to my object? Seems an awful amount of effort where proper inheritance would expose them by default...
    – dKen
    May 4, 2022 at 9:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.