Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter setting property in Map causes UnsupportedError (Unsupported operation: read-only)

Tags:

flutter

dart

I have a method inside a state class which calls setState, however whenever it is called it throws a UnsupportedError (Unsupported operation: read-only) and gives no other information. Can you see anything wrong with my code that would make it do this? I seems like this should be pretty straightforward...

Future _uploadFile(imageFile, imageFilename, String imageNumber) async {
    _user = await DBProvider.db.getUser();
    final FirebaseStorage _storage = FirebaseStorage(storageBucket: 'gs://circle-fc687.appspot.com');
    StorageReference _storageRef = _storage.ref().child('users').child('${_user['uid']}').child('$imageFilename');

    final Directory systemTempDir = Directory.systemTemp;

    final File file = await File('${systemTempDir.path}/$imageFile').create();

    StorageUploadTask _uploadTask = _storageRef.putFile(file);

    await _uploadTask.onComplete;
    print('Upload complete');
    String downloadLink = await _storageRef.getDownloadURL();

    setState(() {
      _user['imageOne'] = downloadLink;
    });
}

Edit calling setState is not the problem, as trying to update a Map property _user['imageOne'] = downloadLink; from within this method also causes the same error. This variable is not a final or anything like that, just Map<String, dynamic>

like image 661
Garrett Avatar asked Nov 14 '19 11:11

Garrett


1 Answers

Usually DBs return immutable/unmodifiable data, so you have to clone it before changing:

final newUser = {
  ..._user,
  'imageOne': downloadLink
};

or

final newUser = Map.of(_user);
newUser['imageOne'] = downloadLink;

Though an unmodifiable map is inherited from the same Map class, it has a different runtime type that doesn't actually support []= operation.

like image 109
Igor Kharakhordin Avatar answered Nov 03 '22 21:11

Igor Kharakhordin