2

I have some flutter code which looks like this:

class InputWithValidation extends StatelessWidget {
  InputWithValidation({this.fieldName, this.accessor});

  final String fieldName;
  final ModelAccessor accessor;

  Widget build(context) {

    var elem = FooDataDictionary.of(context).dataElement(fieldName);

    return Container(
        margin: EdgeInsets.all(inputMargin),
        child: TextFormField(
          keyboardType: elem.keyboardType,
          initialValue: elem.getAsString(accessor),
          autovalidate: true,
          validator: elem.validate,
          onSaved: (val) {
            elem.setFromString(accessor, val);
          },
          decoration: InputDecoration(
            hintText: FooLocalizations.of(context).hint(fieldName),
            labelText: FooLocalizations.of(context).label(fieldName)),
        ));
  }
}

I want to refactor this to pull out the TextFormField so I can re-use it elsewhere without hardcoding the use of a margin.

My first attempt at this was to write:

class DataElementTextFormField extends TextFormField
{
  final DataElement dataElement;
  final ModelAccessor accessor;

  DataElementTextFormField(this.dataElement, this.accessor) :
      super(
        keyboardType: dataElement.keyboardType,
        initialValue: dataElement.getAsString(accessor),
        autovalidate: true,
        validator: dataElement.validate,
        onSaved: (val) {
          dataElement.setFromString(accessor, val);
        },
        decoration: InputDecoration(
          hintText: FooLocalizations.of(context).hint(fieldName),
          labelText: FooLocalizations.of(context).label(fieldName)),
      );
}

However the hintText / labelText lines no longer work because they require the BuildContext to get the proper localization instance. This has me momentarily stumped as I'm not sure the right way to subclass a widget like this.

So my question is somewhat two-fold:

  1. What is the proper way to subclass a StatefulWidget and allow access to the BuildContext?
  2. Given I'm struggling with #1, is it better to simply wrap widgets to add additional functionality vs subclassing them? What is the "best practice"?
Doug Donohoe
  • 367
  • 1
  • 3
  • 11

1 Answers1

2

In general, composition is preferred over inheritance, even for the SDK's widgets. If you inherit, you really need to dive deeply into the parent class and ensure that you're respecting all the protocols. With composition, you can simply look at the published API, and follow the rules there.

Randal Schwartz
  • 39,428
  • 4
  • 43
  • 70