Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add to an existing list - got Unsupported operation: Cannot add to an unmodifiable list

Tags:

flutter

I am trying to add to a List which results in Unsupported operation: Cannot add to an unmodifiable list

But message list is not final, why can't I add Items to it?

class Chat {
  final String uuid;
  final User receiverUser;
  List<Message> messages;

  Chat({this.uuid, this.receiverUser, this.messages = const []});   
}

In my provider I have a send message method

  void send(String receiverUUID) async {
    Message message = Message(
        message: messageController.text,
        receiverUUID: receiverUUID,
        timestamp: DateTime.now());

    await _messageApi.send(message);

    Chat chat = await _findOrCreate(receiverUUID);    
    /// FIXME Unhandled Exception: Unsupported operation: Cannot add to an unmodifiable list
    chat.messages.add(message);

    notifyListeners();
  }
like image 228
combi35 Avatar asked Feb 02 '26 16:02

combi35


1 Answers

Note: if messages was final you could still add items to that list. The problem is that messages is being assigned to the default const[] in your constructor.

Instead of:

chat.messages.add(message);

Try this:

chat.messages = [...chat.messages, message];

... is the Spread Operator. This line will create a new list with message at the end.

You could also use List.from() combined with ..:

chat.messages = List.from(chat.messages)..add(message);

Here, .. is the Cascade Notation. It will add message to the new list but the list will be returned instead of the result of the add method (that would be void).

You could also initialize the messages with a non const []:

class Chat {
  final String uuid;
  final User receiverUser;
  List<Message> messages;

  Chat({this.uuid, this.receiverUser, List<Messages>? messages})
    : messages = messages ?? [];   
}
like image 101
Thierry Avatar answered Feb 04 '26 06:02

Thierry