morganXap
morganXap

Reputation: 45

Refresh listview builder with deleting an element

I have a simple ListView.builder which create each item in its own widget

the parent, stateful (using a futureBuilder) :

child: ListView.builder(
  itemCount: snapshot.data.length,
  itemBuilder: (context, index) {
  Conversation conversation = snapshot.data[index];
     return ConversationSingle(
         conversation: conversation,
     );
},

This part is working fine.

Now, I need to delete some of those widget by tapping another widget (classic)

the children, stateful too:

  child: GestureDetector(
    onTap: () async {
      bool deleted =
          await MyWS().delete(widget.conversation);
      print(deleted); // todo refresh parentlist
    },
    child: SvgPicture.asset(
      getAssetImage('corbeille.svg'),
    ),
  ),

Usualy, i would have pass a param inside the children to refresh the list thanks to a ValueChanged and using a simple column (i wasn't using any ListView before)

But here, data are displayed thanks the itemBuilder, and I can't really get how to refresh my list.

Upvotes: 0

Views: 791

Answers (2)

Jahidul Islam
Jahidul Islam

Reputation: 12575

call with setState()

GestureDetector(
                onTap: () async {
                  setState(() {
                      conversations.remove(widget.conversation);
                  });
                  // todo refresh parentlist
                },
                child: SvgPicture.asset(
                  getAssetImage('corbeille.svg'),
                ),
              )

Upvotes: 2

morganXap
morganXap

Reputation: 45

Ended up by passing a callback function from my parent to my children :

  child: GestureDetector(
    onTap: () async {
      bool deleted =
          await ConversationWS().deleteConversation(widget.conversation);
      if (deleted) {
        widget.onTap(widget.conversation);
      }
    },

I've saved my snapshot value in a global variable

conversations = snapshot.data;

And remove it in my parent widget

  void deleteItemConversation(Conversation conversation) {
    setState(() {
      conversations.remove(conversation);
    });
  }

It's working properly, but if you have better/cleaner solution, don't hesitate to share it

Upvotes: 0

Related Questions