Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter TexField and TextFormField duplicates text when using initial value or controller to set initial text

Within a flutter application that has TextField or TextFormField the text can get duplicated upon first time data entry.

When first entering a keypress, within a field that already has text pre-filled, the text duplicates then your keypress is attached.

I am experiencing something that exhibits this behavior on my Samsung Galaxy S7, S8 and S9 (only devices I have to test with). This doesn't occur within the emulator (Galaxy Nexus9 and Pixel 2).

If I place a space at the end of the field, this problem doesn't happen, however, if I tap in middle of a pre filled field (using controller or initialValue) and press a key it does occur.

Here is a barebones source example:

class SampleTextFormPage extends StatefulWidget {
    @override
    State<StatefulWidget> createState() => new _SampleTextFormPage();
}

class _SampleTextFormPage extends State<SampleTextFormPage> {
    final _scaffoldKey = new GlobalKey<ScaffoldState>();

    TextEditingController _txtController;

    @override
    void initState() {
        super.initState();

        _txtController = TextEditingController(text:'Using Controller');
    }

    @override
    Widget build(BuildContext context) { Scaffold scaffold = new Scaffold(
        key: _scaffoldKey,
        appBar: new AppBar(
            title: new Text('Text Entry',
                style: const TextStyle(
                    color: Colors.white)
            ),
            backgroundColor: Colors.indigo
        ),
        body:  Column(children: [
            //field 1
            TextField(
                 autocorrect: false,
                 autofocus: true,
                 controller: _txtController,
            ),

           //field 2
           TextFormField(
               autocorrect: false,
               autofocus: true,
               initialValue: 'Using initialValue',
           )
        ])
    );

    return scaffold;
    }
}

Note: I am on the latest release of flutter and I have reverted to multiple versions of Flutter (all the way to the first release that supports Dart 2) and this problem still exists.

like image 825
SaltH2OFish Avatar asked Oct 19 '18 14:10

SaltH2OFish


1 Answers

I had same issue and fixed it with this simple temporary solution: just add to initialValue's end a space. Example:

initialValue: controller.text + ' ',
like image 94
Wingear Avatar answered Oct 06 '22 19:10

Wingear