flutter-form-builder-ecosystem / flutter_form_builder

Simple form maker for Flutter Framework
https://pub.dev/packages/flutter_form_builder
MIT License
1.48k stars 535 forks source link

Internal field 'isDirty' flag is reset too late. #1370

Open Adam-Langley opened 7 months ago

Adam-Langley commented 7 months ago

Is there an existing issue for this?

Package/Plugin version

9.2.1

Platforms

Flutter doctor

Flutter doctor ```bash ```

Minimal code example

Code sample ```dart FormBuilderTextField( name: 'description', initialValue: state.description, decoration: InputDecoration( suffixIcon: Builder( builder: (context) { var fb = FormBuilder.of(context)!; if (fb.fields['description']!.isDirty){ return Icon(Icons.undo, size: 16, color: Colors.green,); } else { return SizedBox(); } } ), labelText: 'Description', ), onChanged: (value) { var field = FormBuilder.of(context)!.fields['description']!; if (field.initialValue == field.value && field.isDirty) { field.reset(); } setState(() {}); }, ), ```

Current Behavior

2 issues.

  1. Editing a text field (any field I believe in fact) to return it to its initialValue, does not reset its "isDirty" flag to false.
  2. Attempting to overcome issue 1, by manually calling "reset" on the field after changing it causes stack overflow, because the '_isDirty' internal field is not reset until AFTER setState is called.

Issue 1 may be a misguided expectation on my part. I havent found any documentation (nor tests for that matter) that would imply the isDirty should reset - however, I believe it a bug that it doesnt - as to have a field that has been manually returned by the user to original value should consider it "isTouched" but not "isDirty" - otherwise what's the point of "isTouched"? I hope to see some added tests that exercise this behavior.

Issue 2 can be seen, where in my example code, I am (during onChanged) checking if the "value" and "initialValue" match, and assuming "isDirty" is still "true", I call "reset" on the field. Unfortunately, in form_builder_field.dart, you will see this:

  @override
  void reset() {
    super.reset();
    didChange(initialValue); // <-- the order of these 2 lines is the problem - it will trigger the onChanged again, with 'isDirty' still true. stack overflow.
    _dirty = false;        // <-----|
    if (_customErrorText != null) {
      setState(() => _customErrorText = null);
    }
    widget.onReset?.call();
  }

Expected Behavior

  1. when a field is changed, isDirty should be reset by the infrastructure if the user returns the field value to match initialValue
  2. when reset() is called on a field, the isDirty flag should be reset before execution is passed outside the class, either by firing hooks, callbask, setState, etc.

Steps To Reproduce

Create a simple form with the 1 field example provided in code.

Aditional information

No response