Home > Software engineering >  Flutter Slidable - How to remove the slidable item from the list when i hit the delete button?
Flutter Slidable - How to remove the slidable item from the list when i hit the delete button?

Time:02-27

I have a simple list of ListTile s that I nested in Slidable widget using the flutter_slidable package. However there is one issue that when I use the delete button, the item stays on the screen, even though it is successfully removed from the list (If i make a hot reload, it will actually get removed from screen). I tried to add a setState method inside the onPressed function but I cannot add it because the SlidableAction widget is a stateless widget. How can I make the item disappear when I tap on this button?

Here is a small video demonstration. I delete two lists with the delete button. They stay on the screen. I go home screen and come back to see they got deleted.

https://streamable.com/td7blf

Here is my code:

 Expanded(
              child: ListView.builder(
                  itemCount: likedNames.length,
                  itemBuilder: (context, index) {
                    return Slidable(
                      key: const ValueKey(0),
                      endActionPane: ActionPane(
                        motion: ScrollMotion(),
                        dismissible: DismissiblePane(onDismissed: () {
                          likedNames.remove(likedNames[index]);
                        }),
                        children: [
                          SlidableAction(
                            onPressed: (context) {
                              likedNames.remove(likedNames[index]); // <- this is the part where I want to do the removing of the item
                            },
                            label: 'Delete',
                            backgroundColor: AppColors.error,
                          ),
                        ],
                      ),
                      child: ListTile(
                        onTap: () {},
                        title: Text(likedNames[index].name),
                        trailing: Icon(Icons.chevron_right),
                      ),
                    );
                  }),
            ),

CodePudding user response:

  onPressed: (context) {
    setState() => likedNames.remove(likedNames[index])            
     },

CodePudding user response:

I've used this solution:

onPressed: (BuildContext context) async { 
        await Provider.of<MyList>(context, listen: false)
        .remove(MyList[index]); 
}

MyList is a separate class:

class MyList extends ChangeNotifier 

Whit this methods:

 final List<String> _myList = [];

 List<String> get items => _myList;

. . .

Future<bool> remove(String item) async {
  _myList.remove(item);
  notifyListeners();
  return true;
   }
  • Related