socramm
socramm

Reputation: 81

Flutter ThemeExtension: What to to if lerp is not support by property

I am Trying to work with flutter ThemeExtension and I don't have quit understood how lerp works.

Here a example ThemeExtension:

enum MyButtonVariant {
  solid,
  soft,
  outlined,
  text,
}

class MyButtonStyle extends ThemeExtension<MyButtonStyle> {
  const MyButtonStyle({
    this.variant,
    this.margin,
  });

  final ButtonVariant? variant;
  final EdgeInsets? margin;

  @override
  ThemeExtension<MyButtonStyle> copyWith({
    MyButtonVariant? variant,
    EdgeInsets? margin,
  }) =>
      MyButtonStyle(
        variant: variant ?? this.variant,
        margin: margin ?? this.margin,
      );

  @override
  ThemeExtension<MyButtonStyle> lerp(
      ThemeExtension<MyButtonStyle>? other, double t) {
    if (other is! MyButtonStyle) {
      return this;
    }

    return MyButtonStyle(
      variant: WHAT SHOULD BE HERE? ,
      margin: EdgeInsets.lerp(margin, other.margin, t),
    );
  }
}

What should be used in the lerp function for variant?

I was thinking that something like this could work:

 variant: t < 0.5 ? variant : other.variant,

Is there a better solution?

Upvotes: 4

Views: 620

Answers (1)

Christopher Perry
Christopher Perry

Reputation: 309

You don't actually have to include all of your properties in the lerp method of your theme extension. The only drawback is that those properties will instantly change from one value to another rather than smoothly interpolating between them. That might not be a problem. Maybe that widget is unlikely to be on screen when the theme changes, or maybe so many other things are smoothly changing all over the screen that most users won't notice one little thing changing instantly.

For your situation in particular, however, I think you could try using a ButtonStyle in your theme extension which does come with its own lerp method. Interpolating between enum values won't ever work, because they are discrete values. Nothing exists between MyButtonVariant.solid and MyButtonVariant.soft.

Upvotes: 1

Related Questions