skip to Main Content

I am writing a mobile Flutter app (using GetX) and have a text field widget which is given an initial value by setting controller.myTextEditingController.text = controller.initialValue;. I want the user to be able to enter any text they want. When I begin editing the textfield, everything works as expected. However, once I click the emoji button on the keyboard to begin typing emojis (as I anticipate many users will), the textEditingController.text reverts back to the original value it was given.

Here are some code snippets:

class MyClassController extends GetxController {
    ...
    late Map<String, String?> getParams;
    late String initalValue;
    TextEditingController myTextEditingController = TextEditingController();
    ...
}

class MyClass extends GetView<MyClassController> {
    ...
    @override
    Widget build(BuildContext context) {
        controller.getParams = Get.parameters;
        controller.initialValue = controller.getParams['key'] ?? '';
        ...
        return Scaffold(
            body: Column(
                ...
                _myTextFieldWidget(),
                ...
            )
        );
    }

    Widget _myTextFieldWidget() {
        controller.myTextEditingController.text = controller.initialValue;
        return TextField(
            ...
            controller: controller.myTextEditingController,
            onChanged: (value) {...},
            onEditingComplete: () {}, // left this empty so that the 'done' button on keyboard does nothing
            ...
        );
    }
}

I’ve tried rewriting the widget, moving it directly in the scaffold, and also changing the scope of the textEditingController and where its text is defined. Nothing is working.

Any help would be greatly appreciated!

2

Answers


  1. To solve this problem, you should only set the initial value of the TextEditingController once.
    It seems that you’re facing this issue because of the way the TextEditingController is being handled in MyClass.
    So, every time _myTextFieldWidget() is called , the controller.myTextEditingController.text is being reset to controller.initialValue

    Login or Signup to reply.
  2. Because you call

    control.myTextEditingController.text = control.initialValue;

    within the build() function.
    Every time you click the emoji button on your soft keyboard, the page is rebuilt, causing your textField controller to reset the text to the initial value.

    Move this line to onInit to ensure that it is not called during page rebuilding.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search