简体   繁体   中英

Create object from type in dart / flutter

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM