Home > database >  Flutter(Dart) cannot remove from unmodifiable list
Flutter(Dart) cannot remove from unmodifiable list

Time:10-01

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"
 },
  ....
]

CodePudding user response:

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.

  • Related