Search code examples
androidflutterwidgetcustom-widgets

Flutter widget wrapped inside custom widget


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?


Solution

  • 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>[...]));