I cannot pass a null value to a key that was initially defined as null.
my host can be either String or null, but it returns the error:
[ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: type 'String' is not a subtype of type 'Null' of 'value'
My Code:
class PreferencesBloc {
final PreferencesRepository repository = PreferencesRepository();
final Map<String, dynamic> _json = {
'login': {
'cnpj': '',
'usuario': '',
'senha': '',
},
'configuracao': {
'host': null,
},
};
void gravar() {
_json['login']['cnpj'] = Empresa().cnpj ?? '';
_json['login']['usuario'] = Usuario().usuario ?? '';
_json['login']['senha'] = Usuario().senha ?? '';
_json['configuracao']['host'] = Configuracao().host; //Error is here
repository.whrite(_json);
}
Future<Map<String, dynamic>> ler() async {
var map = await repository.read();
map ??= _json;
return map;
}
}
Tem como fazer isso? Por que não está permitindo?
2
Answers
I am not sure why but this works. Hope someone explains why.
When you define your
_json
asMap<String, dynamic>
, this means only first layer inside your map can acceptnull
value, I mean you can setconfiguracao
like this:but , what you want is set something inside
configuracao
asdynamic
so you need to do this: