-1

I ran into a weird behavior related to the TextFormField, so I maintained a list of Objects in the parent widget, I'm using the following code to render a list of child widgets

 children: <Widget>[
                        ...childProfiles
                            .map((e) => ChildProfileCard(
                                childProfile: e,
                                removeChildProfile: removeChildProfile))
                            .toList(),

And the ChildProfileCard includes a TextFormField, the code is like the following

TextFormField(
                        decoration: const InputDecoration(
                          contentPadding: EdgeInsets.only(top: 0),
                          hintText: "Enter child's name",
                        ),
                        validator: (value) {
                          if (value == null || value.isEmpty) {
                            return 'Name is required';
                          }
                          return null;
                        },
                      ),

There is a "remove" function that simply removes one of the items from the list like the following

setState(() {
      childProfiles = childProfiles
          .where((childProfile) => childProfile.id != childProfileToRemove.id)
          .toList();
    });

When there are more than two items (two child widgets), I input some texts in the TextFormField in the first child widgets, then I remove the first item, the text will always automatically apply to the second child widget, what did I do wrong? I can confirm the list is correctly updated, but the text behaves strangely.

Before deleting, you can see we have different texts for different widgets Before deleting, you can see we have different texts for different widgets

After deleting, the first widget's text is wrongfully copied over to the next widget, you can see the uuid is the second widget's. After deleting, the first widget's text is wrongfully copied over to the next widget

double-beep
  • 5,031
  • 17
  • 33
  • 41
jjjjjjjman
  • 9
  • 1
  • 3

1 Answers1

0

You should Use any unique key while building ChildProfileCard

ChildProfileCard(key: Key(<ANY UNIQUE VALUE>),)

Example

ChildProfileCard(key: Key(e.id),)
Nilesh Senta
  • 5,236
  • 2
  • 19
  • 27