Search code examples
fluttercastingintegerunhandled

How to parse a String to int and not get the next errors?


Withvar pinU = int.parse(pin.text); I get this error:

E/flutter (16045): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: FormatException: Invalid number (at character 1)
E/flutter (16045):
E/flutter (16045): ^

With var pinU = pin as int; I get this error:

E/flutter (16045): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: type 'String' is not a subtype of type 'int' in type cast

I'm trying to pass a PIN to the database helper function to get the results. Here is my complete function:

login2() async {
    var usernameU = username.text;
    var pinU = int.parse(pin.text);

    await DBProvider.db.getUser(usernameU, pinU).then((tempUser) {
      Navigator.push(context as BuildContext,
          MaterialPageRoute(builder: (context) => const WelcomePage()));
    }).catchError((err) {
      // ignore: avoid_print
      print('Error: $err');
    });
  }

I need to pass a int, but this error is persistent.


Solution

  • Instead of var use int as datatype.

    int pinU = int.parse(pin.text ?? "0");