本文介绍了如何在Flutter中重用非Widget类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我们应该在Flutter中使用通过继承构成.当我们谈论 Widgets 时,效果很好.

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

但是当类不是 Widget 时我应该怎么办?例如,我希望我的 TextFields 在某些屏幕中的 InputDecoration 中具有一组特定的值.

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.

我应该扩展 InputDecoration 吗?如何在许多TextField中重用此特定的 InputDecoration ?

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

按照RémiRousselet的指导,我扩展了 InputDecoration .这是最终结果:

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);
}

推荐答案

好的.实际上,请勿扩展窗口小部件"仅限于此:窗口小部件.

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

限制"背后的真正原因是,由于 build 的工作方式,扩展的窗口小部件不允许正确更改窗口小部件的样式.因此,扩展小部件没有任何意义.

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!

Flutter中已经有许多示例可用.例如, Alignment AlignmentGeometry 的子类.

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

这篇关于如何在Flutter中重用非Widget类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 01:14