Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter(Dart) cannot remove from unmodifiable list

I am using tinder swipe cards. It has the following property:

          swipeCompleteCallback:
               (CardSwipeOrientation orientation, int index) {
                    
                    updateStack(index);

               },
            ),

updateStack function:

    class _TinderCardsState extends State<TinderCards>
    with TickerProviderStateMixin {
      List lstUsers = [];
      int lstUsersLength = 0;
     
     @override
     void initState() {
          super.initState();
          setState(() {
            lstUsers = users;
            lstUsersLength = users.length;
          });
      }

      void updateStack(int index) {
          setState(() {
           
              lstUsersLength = lstUsersLength - 1;
              lstUsers.removeAt(index);
          });
     }

So basically just trying to remove the top card from the stack. I am getting the above error even when it is a stateful widget. Why am I getting this error?

The data (just a dart file with a list, no class or anything):

      const List users = [
{
 "id": "p1",
 "name": "John Doe",
 "age": "44",
 "imageUrl":
    "assets/images/anastasia-vityukova-unsplash-blackandwhiteimage.png",
"profession": "Financial Consultant"
 },
  ....
]
like image 319
who-aditya-nawandar Avatar asked Jun 07 '26 13:06

who-aditya-nawandar


2 Answers

Remove const before List users = [...].

You're declaring users as a compile-time constant. That's what makes it unmodifiable.

In dart, objects are passed by reference. When you write lstUsers = users; lstUsers becomes a 'view' of users and then becomes unmodifiable as well.

Another way to avoid that is : lstUsers = users.toList(). It then gives lstUsers the value of a new list created from users.

like image 86
Tanguy Avatar answered Jun 10 '26 03:06

Tanguy


Heres a simple solution

Since your list is immutable you must create a new list but don't make it an instance if the original just make a copy.

List<OnlineChannelUser> userList = List.from(response.data); 
userList.removeWhere((item) => item.uid == currentUid);
print(userList);  //new modified list
like image 44
Londokuhle Avatar answered Jun 10 '26 02:06

Londokuhle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!