Search code examples
fluttertextfieldemoji

Flutter TextField TextEditingController reverts text to original value after emoji button is clicked


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!


Solution

  • 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.