简体   繁体   中英

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'. 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);
},
TextFormField(
     keyboardType: TextInputType.number,
      controller: TextEditingController()
      ..text = '${profileModel.phonenumber}',

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);

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM