1

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?

Ravi Garg
  • 1,378
  • 12
  • 23
Tobias H.
  • 426
  • 1
  • 6
  • 18

2 Answers2

1

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.

OMi Shah
  • 5,768
  • 3
  • 25
  • 34
0
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>[...]));
Ravi Garg
  • 1,378
  • 12
  • 23