skip to Main Content

im trying to divide a number by 23 in flutter

I expected to directly get a number back but instead i got this error

The operator ‘/’ isn’t defined for the type ‘String’.
Try defining the operator ‘/’.

My code is:

  print(textEditingController.text/23);

2

Answers


  1. The type of textEditingController.text is String and a String doesn’t have a divide operation.

    The solution is to convert the textEditingController.text String to a number before doing the divide operation like this:

     final textAsNumber = num.tryParse(textEditingController.text) ?? 0;
      
     print(textAsNumber/23);
    

    The first line of code above means we try parsing the text (and setting textAsNumber to a num type and if it the text can’t be parsed to a num (thereby returning null), we set textAsNumber to0.

    Login or Signup to reply.
  2. It’s because you’re parsing it as a text, not a number variable, try to change it to

    print(double.parse(textEditingController.text)/23);
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search