ListView with StatefulWidget

850 views
Skip to first unread message

Idan Aizik-Nissim

unread,
Oct 4, 2017, 10:45:44 AM10/4/17
to Flutter Dev
Hi,

I'm facing a problem with ListView.builder,
using itemBuilder to build a StatefulWidget as a ListItem.

The problem is that after changing the list (removing item from the middle, adding at 0 index, etc...)
the props on the ListItems are all wrong.

Examples

* Adding:

-- LIST --

1. A
2. B

Adding C:

1. A
2. B
3. B

* Removing:

-- LIST --

1. A
2. B
3. C

Removing 2. B:

-- LIST --
1. A
2. B


After debugging I find out that although the array of items is order correctly (as the example [A,B,C] => removing =>  [A,C]),
the itemBuilder is iterating again over the list of item but when creating the new ItemStatefulWidget passing in the correct item,
the createState of the StatefulWidget isn't get called again...

Is there anyway to force a recreation of the state,
Are there any good practices for Stateful ListItems?

Thanks in advance,
Idan

Idan Aizik-Nissim

unread,
Oct 4, 2017, 11:20:45 AM10/4/17
to Flutter Dev
I think it as something to do with identifying the ListItem.
when adding on index 0 (zero)
the state of the previous item of the zero index is attached to the new item.
when the iterator reached the last index (which is new) a new state is created with the item in the last index,
resulting in duplicating of the last item in the list and not adding the new one.

1. A
2. B

Adding C:

expected:

1. C
2. A
3. B

actual:

1. A
2. B
3. C

🤔 maybe something with key or some way giving an id to the statefulWidget...

let the exploring continue! 🕵🏻

Idan Aizik-Nissim

unread,
Oct 4, 2017, 11:23:10 AM10/4/17
to Flutter Dev
** actual is:

1. A
2. B
3. B

🤦🏻‍♂️

Idan Aizik-Nissim

unread,
Oct 4, 2017, 11:43:49 AM10/4/17
to Flutter Dev
😁 SOLVED!

Yes, all I need was a 🔑:

MyStatefulListItem(Key key, Item item, ...) : super(key: key)

🕺

tagir.m...@gmail.com

unread,
Dec 4, 2017, 5:07:40 PM12/4/17
to Flutter Dev
Thanks so much for the following through. 
I've spent almost a day on it. Tried providing key on the internal ListTile of my state, but nothing worked until I called `super(key: ...)` on my stateful widget.
Reply all
Reply to author
Forward
0 new messages