Home > Enterprise >  How to apply toStringAsFixed() to a templated value class member?
How to apply toStringAsFixed() to a templated value class member?

Time:08-26

Say we have a template class of type T that defines value being of that class T


class BmsEditableValue<T> extends StatelessWidget {
  /// Value to be edited
  final T? value;
}

I wan to apply toStringAsFixed() on value when it is a double, but the following makes toStringAsFixed() not being defined:


value! is double
                ? value!.toFixedString(decimals!)
                : value;

CodePudding user response:

Finally I did that:

 (value! as double).toStringAsFixed(decimals!)

CodePudding user response:

You can use a local variable to allow automatic type promotion to occur:

Object? v = value;
var result = (v is double)
  ? v.toStringAsFixed(...)
  : value;

Note that v must be declared as Object or dynamic and not as T because Dart will not automatically perform type promotion across types that are not statically known to be related.

  • Related