Home > Net >  Create object from type in dart / flutter
Create object from type in dart / flutter

Time:05-23

Is there a way to create an object from type in dart? Example of what I want to do but it is not working:

// select the button type based on certain value (valid in this case)
final button = valid ? ElevatedButton : OutlinedButton;
// create the correct button
button(....) // this does not work

Is there a way to make this work?

I don't want to have code that looks like this because there will be duplications:

    if (valid) {
      return OutlinedButton(
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            SvgPicture.asset(image, width: 24.0),
            Text(label),
            Opacity(opacity: 0, child: SvgPicture.asset(image, width: 24.0)),
          ],
        ),
        onPressed: () async => await updatePassword(
          context: context,
          ref: ref,
          newPassword: ref.read(updatePasswordControllerProvider).newPassword,
        ),
      );
    } else {
      return ElevatedButton(
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            SvgPicture.asset(image, width: 24.0),
            Text(label),
            Opacity(opacity: 0, child: SvgPicture.asset(image, width: 24.0)),
          ],
        ),
        onPressed: null,
      );
    }

CodePudding user response:

Here, you can create widget like,

// select the button type based on certain value (valid in this case)
final button = valid ? ElevatedButton() : OutlinedButton();

And handle the events like press or anything above

And when ever you want to use that button simply add the button object not the parentheses.

Hope this will resolve your issue.

CodePudding user response:

No, you can't do that as these types don't have same properties. Also the parent class of these types is not a concrete class which could you have used.

In Flutter, you can do:

final button = valid ? ElevatedButton(...) : OutlinedButton(...);

Update:

Why don't you just refactor duplicated Row in a getter like this:

Row get row => Row(
  mainAxisAlignment: MainAxisAlignment.spaceBetween,
  children: [
    SvgPicture.asset(image, width: 24.0),
    Text(label),
    Opacity(opacity: 0, child: SvgPicture.asset(image, width: 24.0)),
  ],
);

After this you can use:

if (valid) {
  return OutlinedButton(
    child: row,
    onPressed: () async => await updatePassword(
      context: context,
      ref: ref,
      newPassword: ref.read(updatePasswordControllerProvider).newPassword,
    ),
  );
} else {
  return ElevatedButton(
    child: row,
    onPressed: null,
  );
}
  • Related