Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter TextField is losing data when focus changes

I have textformfields like this : If i don't define a keyboardType for the second textformfield, there is no problem when i go through from first one to second field, i don't lose the first field's input. But if i define keyboardtype in my code, it loses the first field's data when i click on the second field.

Note : I am using riverpod as State Management.


class NewTx extends StatelessWidget {
  final TextEditingController titleController = TextEditingController(text: '');
  final TextEditingController priceController = TextEditingController(text: '');

  @override
  Widget build(BuildContext context) {
    return Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
      TextFormField(
          controller: titleController,
          decoration: InputDecoration(hintText: 'Title')
          ),
      TextFormField(
          keyboardType: TextInputType.number,
          controller: priceController,
          decoration: InputDecoration(hintText: 'Title')),
      Container(
          alignment: AlignmentDirectional.bottomEnd,
          child: IconButton(
              icon: Icon(Icons.add),
              onPressed: () => context.read(transactionProvider).addTx(
                  Transaction(titleController.text, priceController.text))))
    ]);
  }
}


Edit : riverpod_hooks and useTextEditingController is working perfectly.(Another solution than stateful widget.)

like image 972
devberkay Avatar asked Sep 06 '25 03:09

devberkay


1 Answers

I think issue is not in loosing focus, but rather in the fact that widget is rebuilt, it's class recreated and as consequence - controllers keeping text recreated.

I suggest changing NewTx to stateful widget and moving controllers to its state.

like image 81
Alex Radzishevsky Avatar answered Sep 07 '25 19:09

Alex Radzishevsky