Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter ThemeExtension: What to do 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?

like image 565
socramm Avatar asked Jan 18 '26 07:01

socramm


1 Answers

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.

like image 141
Christopher Perry Avatar answered Jan 21 '26 01:01

Christopher Perry