Search code examples
flutterlayout

How to create a wrapper widget and pass children and properties to it in flutter


I have two pages with the same layout

In react I would create a wrapper, import it and pass the children, so both pages share the same wrapper.

<Wrapper someproperty={1}>
  <div>content page 1</div>
</Wrapper>

<Wrapper someproperty={2}>
  <div>content page 2</div>
</Wrapper>

Is there an equivalent for this in flutter? Any other option is very welcome, like a shared class or something, thank you


Solution

  • Normally I used the Class MetaData.

    The documentation: https://api.flutter.dev/flutter/widgets/MetaData-class.html

    Example of usage:

    class CustomText extends StatelessWidget {
      const CustomText({
        Key key,
        this.text,
      }) : super(key: key);
    
      final String text;
    
      @override
      Widget build(BuildContext context) {
        final WrapperWidget wrapperWidget = context.findAncestorWidgetOfExactType();
        return Text(
          "text ${wrapperWidget.metaData.toString()}" ??
              wrapperWidget.metaData.toString(),
        );
      }
    }
    
    class WrapperWidget extends MetaData {
      const WrapperWidget({
        Widget child,
        int someProperty,
      }) : super(
              child: child,
              metaData: someProperty,
            );
    }
    
    
    /// declaration
    final component = WrapperWidget(
                child: CustomText(text: "content page"), someProperty: 1);