我无法将 null 值传递给最初定义为 null 的键。 我的主机可以是 String 或 null,但它返回错误:
[ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: type 'String' is not a subtype of type 'Null' of 'value'
我的代码:
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?你是否允许?
我不知道为什么,但这有效。希望有人解释一下原因。
var nullableString;
final Map<String, dynamic> _json = {
'login': {
'cnpj': '',
'usuario': '',
'senha': '',
},
'configuracao': {
'host': nullableString,
},
};