Home > Net >  Flutter generic function callback
Flutter generic function callback

Time:05-10

can you comment?

typedef ButtonChangedCallback = void Function<T>(T value);

class MyWidget<T> extends StatefulWidget {
  ButtonChangedCallback? onCallback;
  const MyWidget(
      {required Key key,
      this.onCallback})
      : super(key: key);

I would like to create such template widget to be used with different enums. So it can signal what value from the enum was selected. But I am unable to find how to later assign to the "onCallback" method.

MyWidget(
        key: const Key("RadioControls"),
        onCallback: <MyEnum>(MyEnum value) =>
          setState(() {
            someSettings.value = value;
          }),
      )

This does not work with Value of type MyEnum can not be assigned to variable of type MyEnum By some experiments I discovered that inside the lambda does not seem to correspond to MyEnum as defined before.

EDIT: Solution

typedef ButtonChangedCallback<T> = void Function(T value);

class MyWidget<T> extends StatefulWidget {
  ButtonChangedCallback<T>? onCallback;

used as

MyWidget<MyEnum>(
        key: const Key("RadioControls"),
        onCallback: (MyEnum value) =>
          setState(() {
            someSettings.value = value;
          }),
      )

CodePudding user response:

When you do:

typedef ButtonChangedCallback = void Function<T>(T value);

class MyWidget<T> extends StatefulWidget {
  ButtonChangedCallback? onCallback;

You're declaring that ButtonChangedCallback must be a generic function. Whatever callback is assigned to MyWidget.onCallback must itself be generic. That is, you would only be able to use it as:

MyWidget(onCallback: <T>(T x) { ... });

In the above, T is the name of the type parameter to your generic, anonymous function. It is not a type argument. T could be named anything, and in your attempt, you happened to name it MyEnum, so you ended up in a confusing situation where a generic type parameter had the same name as an actual type.

Additionally, the type parameter for the function would be unrelated to the type parameter for MyWidget.

What you probably want is to for the typedef to be generic and for the Function object to not be:

typedef ButtonChangedCallback<T> = void Function(T value);

class MyWidget<T> extends StatefulWidget {
  ButtonChangedCallback<T>? onCallback;

and now you can use it as:

MyWidget<MyEnum>(
  onCallback: (value) =>
    setState(() {
      someSettings.value = value;
    }),

CodePudding user response:

This way should work:

class MyWidget<T> extends StatefulWidget {
  final Function<T>? callback;
  const MyWidget({required this.key, this.callback}) : super(key: key);
}

And you instantiate the widget this way:

MyWidget<MyEnum>(
  key: const Key("RadioControls"),
  callback: (MyEnum value) {
    setState((){
      someSettings.value = value;
    });
  }
)
  • Related