我想解析,如“1”或“32.23”串到整数和双打。 我怎样才能用飞镖做到这一点?
Answer 1:
您可以解析字符串与整数int.parse()
例如:
var myInt = int.parse('12345');
assert(myInt is int);
print(myInt); // 12345
需要注意的是int.parse()
接受0x
前缀字符串。 否则,输入被处理为基础-10。
您可以解析字符串与双double.parse()
例如:
var myDouble = double.parse('123.45');
assert(myDouble is double);
print(myDouble); // 123.45
parse()
将抛出出现FormatException,如果它不能解析输入。
Answer 2:
在省道2 int.tryParse可用。
它返回null无效的投入,而不是抛出。 您可以使用它像这样:
int val = int.tryParse(text) ?? defaultValue;
文章来源: How do I parse a string into a number with Dart?