Respuestas:
Puede analizar una cadena en un número entero con int.parse(). Por ejemplo:
var myInt = int.parse('12345');
assert(myInt is int);
print(myInt); // 12345
Tenga en cuenta que int.parse()acepta 0xcadenas con prefijo. De lo contrario, la entrada se trata como base 10.
Puede analizar una cadena en un doble con double.parse(). Por ejemplo:
var myDouble = double.parse('123.45');
assert(myDouble is double);
print(myDouble); // 123.45
parse() lanzará FormatException si no puede analizar la entrada.
En Dart 2 int.tryParse está disponible.
Devuelve nulo para entradas no válidas en lugar de lanzar. Puedes usarlo así:
int val = int.tryParse(text) ?? defaultValue;
Según dardo 2.6
El onErrorparámetro opcional de int.parseestá obsoleto . Por lo tanto, debería usar int.tryParseen su lugar.
Nota : Lo mismo se aplica a double.parse. Por lo tanto, utilice double.tryParseen su lugar.
/**
* ...
*
* The [onError] parameter is deprecated and will be removed.
* Instead of `int.parse(string, onError: (string) => ...)`,
* you should use `int.tryParse(string) ?? (...)`.
*
* ...
*/
external static int parse(String source, {int radix, @deprecated int onError(String source)});
La diferencia es que int.tryParseregresa nullsi la cadena de origen no es válida.
/**
* Parse [source] as a, possibly signed, integer literal and return its value.
*
* Like [parse] except that this function returns `null` where a
* similar call to [parse] would throw a [FormatException],
* and the [source] must still not be `null`.
*/
external static int tryParse(String source, {int radix});
Entonces, en su caso, debería verse así:
// Valid source value
int parsedValue1 = int.tryParse('12345');
print(parsedValue1); // 12345
// Error handling
int parsedValue2 = int.tryParse('');
if (parsedValue2 == null) {
print(parsedValue2); // null
//
// handle the error here ...
//
}
void main(){
var x = "4";
int number = int.parse(x);//STRING to INT
var y = "4.6";
double doubleNum = double.parse(y);//STRING to DOUBLE
var z = 55;
String myStr = z.toString();//INT to STRING
}
int.parse () y double.parse () pueden arrojar un error cuando no pudo analizar la cadena
int.parse()y double.parse()puede arrojar un error cuando no pudo analizar la cadena. Desarrolle su respuesta para que otros puedan aprender y entender mejor el dardo.
puede analizar la cadena con int.parse('your string value');.
Ejemplo:- int num = int.parse('110011'); print(num); \\ prints 110011 ;