Flutter widget wrapped inside custom widget

180

Solution 1

class CustomBox extends StatelessWidget {

  final Widget childWidget;
  CustomBox({this.childWidget});

  @override
  Widget build(BuildContext context) {

    return Padding(
      padding: const EdgeInsets.fromLTRB(15, 15, 15, 15),
      child: Container(
        margin: EdgeInsets.fromLTRB(30, 30, 30, 30),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(45),
        ),

        child: this.childWidget,

      ),
    );
  }
}

Access it through

CustomBox(childWidget: Text('Hello'));

or

CustomBox(childWidget: Row(children: <Widget>[...]));

Solution 2

You can pass your child widget in a dynamic way via the use of the constructor. You can do like this:

class CustomBox extends StatelessWidget {
  final Widget childWidget;
  CustomBox(this.childWidget);

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.fromLTRB(15, 15, 15, 15),
      child: Container(
          margin: EdgeInsets.fromLTRB(30, 30, 30, 30),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(45),
          ),
          //custom child here
          child: childWidget),
    );
  }
}

and when you need to use, do like this:

CustomBox(Text('Text')). Just replace Text('Text') with your choice of widget.

Share:
180
Tobias H.
Author by

Tobias H.

Updated on December 23, 2022

Comments

  • Tobias H.
    Tobias H. over 1 year

    I have a custom widget named CustomBox:

    class CustomBox extends StatelessWidget {
    
      @override
      Widget build(BuildContext context) {
    
        return Padding(
          padding: const EdgeInsets.fromLTRB(15, 15, 15, 15),
          child: Container(
            margin: EdgeInsets.fromLTRB(30, 30, 30, 30),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(45),
            ),
    
            //custom child here
    
          ),
        );
      }
    }
    

    Where I put custom child here, I want to put any child inside, but from the widget-tree. See this custom widget is a box (with specific borders and stuff). And I want to be able to blub this into my app whenever and put say an Image or some text (maybe also a row with children) on the inside. How do I do that, without putting the new widget inside this custom widget?

    • Jitesh Mohite
      Jitesh Mohite over 3 years
      what is the error you are getting if you are adding child inside custom widget
  • pskink
    pskink over 3 years
    and by convention it should be named child, not childWidget