Home>

In case of an erroneous input, I need to leave the cursor in the same place, and it returns to the beginning of the line all the time. Therefore, before entering, I want to save the position of the cursor, and on error, return the position to the saved position. How do I get the position of the cursor?

  • Answer # 1

    I came up with this solution:

    onChanged: (String text)
                    {
                      var textDouble= double.tryParse (text);
                      var selection= _controller.selection; //Save the current cursor position
                      if (textDouble!= null)
                      {
                        if (textDouble >
     1000) //Wrong input
                          {
                            _controller.text= oldText; //Return the old value
                            _controller.selection= TextSelection.fromPosition (
                                TextPosition (offset: selection.baseOffset -1)); //Leave the cursor at the saved location
                            return;
                          }
                        _controller.selection= TextSelection.fromPosition (
                            TextPosition (offset: _controller.text.length));
                        oldText= _controller.text; //Re-store the old value
                      }
                    }