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:
- What is the proper way to subclass a
StatefulWidget
and allow access to theBuildContext
? - 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"?