2

I am using Cubit to develop my platform. I have a custom form to edit a record.

All the TextFormFields receive an initial value.

My problem is that when the user finishes editing each TextFormField, I need to update the state of my cubit.

I can't use onChanged because TextFormField loses focus each time the state is updated.

I can't use onSaved because it just updates the value of the last TextFormField because of how the state is updated. It needs to update after each field is edited and not after all fields are edited.

My last option is using the onFieldSubmitted because it will run when the user stops editing each field. It only runs when the user presses ENTER but, I need to run it when the focus is lost.

If you think that the code would help, let me know, and I will add it.

Update

The problem is not with the state changing.

I am using a Stepper widget, and the number of steps changes depending on some inputs.

When it changes, I get this error "widget.steps.length == oldWidget.steps.length" to work around it I gave it a random key each time it's called.

Because of that, the focus is lost.

1 Answers1

1

You can catch focus losing by wrapping TextFormFields with Focus widget.

The 'onFocusChange' catch TextFormField's focus losing.

        Focus(
          onFocusChange: (hasFocus) {
            print('$hasFocus');
            // Todo Something
          },
          child: TextFormField(
            onFieldSubmitted: (input) {
              print('onFieldSubmitted: $input');
            },
          ),
          
        )
KuKu
  • 6,654
  • 1
  • 13
  • 25
  • Using the Focus widget, I will need to use a controller for each field, and I wanted to avoid it if possible. I like to use onChanged, but when I update the state of the cubit, the custom Form widget rebuilds, and it loses focus. There's any workaround that I could do? – Henrique Melo Aug 24 '21 at 19:03
  • The problem is not with the state changing. I am using a Stepper widget, and the number of steps changes depending on some inputs. When it changes, I get this error "widget.steps.length == oldWidget.steps.length" to work around it I gave it a random key each time it's called. Because of that, the focus is lost. – Henrique Melo Aug 24 '21 at 20:15