Home > OS >  A value of type 'int' can't be assigned to a variable of type 'String'
A value of type 'int' can't be assigned to a variable of type 'String'

Time:07-31

A value of type 'int' can't be assigned to a variable of type 'String'. Try changing the type of the variable, or casting the right-hand type to 'String'.

TextFormField(
                    keyboardType: TextInputType.number,
                    controller: TextEditingController()
                      ..text = '${profileModel.phonenumber}',
                    style: TextStyle(
                      color: Colors.black,
                      fontSize: 17,
                      letterSpacing: 1,
                    ),
                    decoration: InputDecoration(
                      border: OutlineInputBorder(),
                      labelText: "Phone Number",
                      hintText: "enter your phonenumber",
                      floatingLabelBehavior: FloatingLabelBehavior.auto,
                      prefixIcon: Icon(Icons.phone),
                      focusedErrorBorder: OutlineInputBorder(),
                    ),
                    onChanged: (text) {
                      number = text as int;
                      print(number);
                    },
                  ),

CastError (type 'String' is not a subtype of type 'int' in type cast)

onChanged: (text) {
 number = text as int;
 print(number);
},

CodePudding user response:

TextFormField(
     keyboardType: TextInputType.number,
      controller: TextEditingController()
      ..text = '${profileModel.phonenumber}',

CodePudding user response:

I will recommend using int.tryParse. Because it can fail on parser too when the input text will not number. If number is not nullable, provide a default value.

number = int.tryParse(text)?? 0;

And if number is string just do

  number = text;

CodePudding user response:

You can write like this :

onChanged: (text) {
 number = int.parse(text);
 print(number);
},

need to change number = text as int; to number = int.parse(text);

  • Related