3

I know we are supposed to use composition over inheritance in Flutter. And that works great when we are talking about Widgets.

But what am I supposed to do when a class is not a Widget? For example, I want my TextFields in some screens to have a specific set of values in their InputDecoration.

Should I extend InputDecoration? How can I reuse this specific InputDecoration in many TextFields?

EDIT: Following Rémi Rousselet's guidance, I extended InputDecoration. Here's the final result:


class LoginInputDecoration extends InputDecoration {
  @override
  InputBorder get errorBorder =>
      UnderlineInputBorder(borderSide: BorderSide(color: AppColors.danger));

  @override
  EdgeInsetsGeometry get contentPadding => const EdgeInsets.symmetric(
        horizontal: Dimens.halfSpace,
        vertical: Dimens.singleSpace,
      );

  @override
  InputBorder get border =>
      UnderlineInputBorder(borderSide: BorderSide(color: AppColors.primary));

  @override
  TextStyle get labelStyle =>
      TextStyle(color: AppColors.white, decorationColor: AppColors.white);

  @override
  InputBorder get enabledBorder =>
      UnderlineInputBorder(borderSide: BorderSide(color: AppColors.primary));

  @override
  TextStyle get hintStyle =>
      TextStyle(color: AppColors.white, decorationColor: AppColors.white);

  LoginInputDecoration({String labelText}) : super(labelText: labelText);
}
Rod
  • 424
  • 2
  • 7
  • 17

2 Answers2

3

Sure. The "don't extend widgets" is really limited to that: widgets.

The real reason behind that "limitation" is that extending widgets do not allow to properly change the style of a widget, due to how build works. So extending widgets do not make sense.

But that reason does not apply to other kinds of objects. So don't worry and go ahead!

There are many examples available in Flutter already. For example, Alignment is a subclass of AlignmentGeometry.

Rémi Rousselet
  • 256,336
  • 79
  • 519
  • 432
  • Thanks! You are right, I managed to solve this using inheritance. I'll update my question with some code to show it. – Rod Aug 09 '19 at 13:09
0

I have extended the Decoration class, the TextInputFormatter and TextFieldValidator class with great success for front end UI development and easy to recommend.

Decoration class to put a dotted line border around Containers. TextInputFormatter for credit card number entry TextFieldValidator for expiry date credit card validation.

user2244131
  • 83
  • 2
  • 10