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();
}
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 ?? [];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With