Russel Bryan Marco
Russel Bryan Marco

Reputation: 1

FormField `_fieldDidChange` causing rebuild in all form fields

Hello is there someway that flutter will allow specific field rebuild rather than forcing all fields to be rebuilt when only one fields is being interacted with?

when state.didChange(v) is called FormState's _fieldDidChange also gets called that invokes that _forceRebuild method when working with large number of forms fields (in my case 100+) this poses performance issues as each interaction causes those fields now to be rebuild every time.

I don't know any workaround other that using ListView.builder() which i am not keen on using for the reason that after i click submit all fields required should be validated and visible for the users to scan through.

Upvotes: 0

Views: 17

Answers (1)

NickolayS
NickolayS

Reputation: 56

  1. Use ValueNotifier or ChangeNotifier for Individual Fields Instead of relying on FormState, manage each field’s state separately using a ValueNotifier or ChangeNotifier. This way, only the relevant field rebuilds when it changes.

Example:

class FieldController extends ChangeNotifier {
  String _value = '';
  String get value => _value;

  void updateValue(String newValue) {
    _value = newValue;
    notifyListeners();
  }
}

Usage in UI:

final controller = FieldController();

TextFormField(
  onChanged: (val) => controller.updateValue(val),
  decoration: InputDecoration(labelText: "Field"),
);

Wrap only the affected part of the UI with ValueListenableBuilder:

ValueListenableBuilder<String>(
  valueListenable: controller,
  builder: (context, value, child) {
    return Text("Current: $value");
  },
);
  1. Use StatefulBuilder for Localized Rebuilds StatefulBuilder allows fine-grained state management for just one field instead of the entire form.

StatefulBuilder( builder: (context, setState) { return TextFormField( onChanged: (val) => setState(() {}), decoration: InputDecoration(labelText: "Optimized Field"), ); }, ); 3. Use GlobalKey for Each Field Each TextFormField can be wrapped in its own FormField with a unique GlobalKey to prevent unnecessary rebuilds.

GlobalKey<FormFieldState> key1 = GlobalKey<FormFieldState>();

TextFormField(
  key: key1,
  onChanged: (val) {
    key1.currentState?.didChange(val);
  },
);
  1. Use flutter_form_builder Package The flutter_form_builder package provides more control over field updates and validation without triggering unnecessary rebuilds.

Upvotes: 0

Related Questions