Home > OS >  The following FormatException was thrown while calling onChanged: Invalid number (at character 1)
The following FormatException was thrown while calling onChanged: Invalid number (at character 1)

Time:06-08

I am trying to clear the initial value from and textfield and give new value, when the textfield is empty i am getting this error.

The following FormatException was thrown while calling onChanged:
Invalid number (at character 1)

^

When the exception was thrown, this was the stack: 
#0      int._handleFormatError (dart:core-patch/integers_patch.dart:129:7)
#1      int.parse (dart:core-patch/integers_patch.dart:55:14)

Below is my code.

  int _currentSliderValue = 1;
  TextEditingController sliderController = TextEditingController();

Column(
            children: [
              Slider(
                value: _currentSliderValue.toDouble(),
                max: 100,
                label: _currentSliderValue.round().toString(),
                onChanged: (double value) {
                  setState(() {
                    _currentSliderValue = value.toInt();
                    sliderController.text = _currentSliderValue.toString();
                    print(_currentSliderValue);
                  });
                },
              ),
              Padding(
                padding: const EdgeInsets.all(0.0),
                child: TextFormField(
                  decoration: InputDecoration(
                    border: OutlineInputBorder(),
                  ),
                  controller: sliderController,
                  onChanged: (text) {
                    setState(() {
                      _currentSliderValue = int.parse(text);
                    });
                  },
                ),
              ),
            ],
          )

How to overcome this issue. i don't get any error when i add any values.

Please help me how to fix this. Thanks in advance.

CodePudding user response:

This error occurs because the int parser couldn't parse the string you're trying to parse. To fix this you should make sure that the value is correct or use int.tryParse(value).

CodePudding user response:

If you wish to allow only numbers in text field add these codes in textfield

keyboardType: TextInputType.number,
        inputFormatters: <TextInputFormatter>[
FilteringTextInputFormatter.digitsOnly,],

As @M.Taha Basiri mentioned the error is because of adding a non integer value in textfield and trying to parse it. You can also add try parse while parsing the text value.

  • Related