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

[General]: Log warning when `patchValue` does not find a corresponding registered field #1407

Open Camerash opened 3 months ago

Camerash commented 3 months ago

Is there an existing issue for this?

Package/Plugin version

9.3.0

What you'd like to happen

In the FormBuilderState.patchValue method, the code takes in the new value map, iteratively search for a registered field with the map key, and calls the field's didChange method if the field is found.

Developers that are not familiar with the inner workings with the library may often wrongly assume the patchValue method updates the value of the form, regardless whether the FormField is present or not. This is often the case in my team of developers when we are using this library. Since conditional rendering is a very common practice in the Flutter framework, one may do something like this:

setState(() {
  new_field_should_render = true;
});

formState?.patchValue({
  "new_field_name": new_value,
});

...

// under build
if (new_field_should_render)
  FormBuilderField(
    name: "new_field_name"
  ),

This will not work as the field has not yet been registered. The workaround is to either use Offstage to make the field always stays inside the widget tree, or to call patchValue a frame later using addPostFrameCallback

However, debugging this is not easy.

I suggest we can add a warning log when patchValue cannot find the respective field using the key inside the map, warning the developer that the field with the given key is not registered and therefore the update to that field is ignored.

Alternatives you've considered

No response

Aditional information

No response