11

i want to get int data entered in the TextField() in flutter, i using TextEditingController:

TextEditingController _section_id = new TextEditingController();

and using this controller in it:

TextField(controller: _section_id,
                keyboardType: TextInputType.number,)

but now, how can i get int data? i try this way by

Repository().placeAddApiProvider(_section_id.text)

but its for just string, and try cast to int,

Repository().placeAddApiProvider(_section_id.text as int)

 but it is not work show me this error:
Unhandled Exception: type 'String' is not a subtype of type 'int' in type cast
E/flutter ( 6950): #0      AddPlaceState.build.<anonymous closure> (package:mosul/src/ui/users/add_place.dart:93:50)
E/flutter ( 6950): <asynchronous suspension>
E/flutter ( 6950): #1      _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:513:14)
E/flutter ( 6950): #2      _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:568:30)
E/flutter ( 6950): #3      GestureRecognizer.invokeCallback (package:flutter/src/gestu...

Thank you

5 Answers 5

22

Update 2023:

int heightValue = int.parse(_heightCon.text);

when we want to get an integer from TextEditingController do like this,

 int var =int.parse(_section_id.text);
Sign up to request clarification or add additional context in comments.

Comments

13

You cannot cast a String to int because they do not inherit from the same parent class. You need to parse it instead.

Repository().placeAddApiProvider(int.parse(_section_id.text))

2 Comments

int.parse(controller.text) results in an error . Unhandled Exception: FormatException: Invalid number (at character 1)
Therefore use int.tryParse(controller.text) if int.parse(controller.text) generates an error
1

sometime we want to use tryParse instead for parse. int qty=int.tryParse(qtyController.text);

Comments

0

inside TextField onChanged

 onChanged: (s) {
  int s = int.parse(
   _section_id.text);
    },

Comments

0

parse string that you get from textfield[Restrict it to enter only digits] to Int and use int.tryParse(String) if you don't worry about the conversion to be successful not or if you do then use int.parse(String)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.