1

I have a StatefulWidget which is built from a list of fields.

It looks something like this:

class MultiFieldForm extends StatefulWidget {
  /// constructor
  const MultiFieldForm(this.fields);

  /// Fields
  final List<Field> fields;

  @override
  _MultiFieldFormState createState() => _MultiFieldForm();
}

class _MultiFieldFormState extends State<MultiFieldForm> {
  /// constructor
  _MultiFieldFormState();

  /// Fields the user has minimized
  List<Field> collapsedFields = [];

  /// Fields the user has filled with the values
  Map<Field,String> filledFields = {};

  @override
  Widget build(BuildContext context) {
    // build code here
  }
}

The state takes this list of fields and creates a form for each field with a text box to fill out, and a button to submit the whole thing.

Now this works, except if a new field is added to the form while the user is filling it out, and entirely new widget is built in the place of the old one. For the user this appear like their form has just been completely wiped. And indeed they have to start over again. This is not ideal, because I actually have new fields appearing all the time.

What I would like to do is have access to the old state when building the new state, so I can copy what the user has already filled and adjust it so that it fits the new form.

This is sort of what didUpdateWidget does, but as far as I can tell, I only get access to the old widget and not its state.

How can I transfer the state of the old widget to the new widget?

Wheat Wizard
  • 3,982
  • 14
  • 34
  • Do you assign controllers to the fields? Can you add that part of your code where you actually add the fields? – Peter Koltai Oct 21 '21 at 11:31
  • @PeterKoltai I don't use any controllers currently because there is really no use for them when the state gets reset. But I'm not sure what difference it makes. I'm trying to prevent the parent state from being reset it shouldn't matter to my problem the exact structure of the form, just that it is dynamic. – Wheat Wizard Oct 21 '21 at 12:13
  • If you create controllers to fields and keep the controllers in a list as a member in your state class, they will keep the state of the fields, the values the user entered. – Peter Koltai Oct 21 '21 at 12:58
  • @PeterKoltai Yes, but that requires the parent state being maintained. Which is why that's my issue, not the individual forms. – Wheat Wizard Oct 21 '21 at 14:02

0 Answers0