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.
Stringをbool、int、doubleの順でパースできる型に変換しその型のまま返します。
変換できない場合は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)
Implementation
dynamic toAny() {
if (isEmpty) {
return "";
}
final b = 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;
}