Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a better way to parse an int in Dart

Tags:

dart

This is several questions about int.parse in Dart...

I know that in Dart we can parse a string as an int and catch exceptions using something like:

try {
  n = int.parse(input.value);
  // etc.
} on FormatException {
  // etc.
}

(Which is fine.)

In the documentation, there is the following description of int.parse:

int parse(String source, int radix, int onError(String source))

When I tried using int.parse with more than one argument, however, I got a complaint from the editor about me using extra arguments. Am I misunderstanding the documentation? And how does one, for example, set the radix?

like image 205
Richard Ambler Avatar asked Mar 08 '13 08:03

Richard Ambler


2 Answers

In Dart 2, int.tryParse is available.

It returns null for invalid inputs instead of throwing. You can use it like this:

int val = int.tryParse(text) ?? defaultValue;

The onError parameter in int.parse is deprecated.

like image 122
kgiannakakis Avatar answered Oct 01 '22 14:10

kgiannakakis


Int.parse uses named, optional parameters.

API:

int parse(String source, {int radix, int onError(String source)})

The { } around params in the parameter list indicate that these are optional, named parameters. (If you had [ ] around params in the parameter list, these would be optional, positional parameters)

Example Usage:

int.parse("123");
int.parse("123", radix:16);
int.parse("123", onError:(source) => print("Source"));
int.parse("123", radix:16, onError:(source) => print(source));
like image 40
Chris Buckett Avatar answered Oct 01 '22 12:10

Chris Buckett