toAny method

dynamic toAny()

Converts a String to a type that can be parsed as bool, int, or double, in that order, and returns the type as is.

If it cannot be converted, it is returned as String.

Stringboolintdoubleの順でパースできる型に変換しその型のまま返します。

変換できない場合はStringのまま返されます。

final text = "100";
final any = text.toAny(); // 100 (int)
final text = "100.9";
final any = text.toAny(); // 100.9 (double)
final text = "false";
final any = text.toAny(); // false (bool)
final text = "abc100";
final any = text.toAny(); // "abc100" (String)

Returns null if itself is Null.

自身がNullの場合nullを返します。

Implementation

dynamic toAny() {
  if (this == null) {
    return null;
  }
  if (isEmpty) {
    return "";
  }
  final b = this!.toLowerCase();
  if (b == "true") {
    return true;
  } else if (b == "false") {
    return false;
  }
  final i = int.tryParse(this!);
  if (i != null) {
    return i;
  }
  final d = double.tryParse(this!);
  if (d != null) {
    return d;
  }
  return this;
}