skip to Main Content

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


  1. I am not sure why but this works. Hope someone explains why.

    var nullableString; 
    
    final Map<String, dynamic> _json = {
        'login': {
          'cnpj': '',
          'usuario': '',
          'senha': '',
        },
        'configuracao': {
          'host': nullableString,
        },
      };
    
    Login or Signup to reply.
  2. When you define your _json as Map<String, dynamic>, this means only first layer inside your map can accept null value, I mean you can set configuracao like this:

    final Map<String, dynamic> _json = {
        'login': {
          'cnpj': '',
          'usuario': '',
          'senha': '',
        },
        'configuracao': null, // <-- this
      };
    

    but , what you want is set something inside configuracao as dynamic so you need to do this:

    void gravar() {
        _json['login']['cnpj'] = Empresa().cnpj ?? '';
        _json['login']['usuario'] = Usuario().usuario ?? '';
        _json['login']['senha'] = Usuario().senha ?? '';
        Map<String, dynamic> newConfiguracao = _json['configuracao'];
        newConfiguracao['host'] = Configuracao().host;
        _json['configuracao'] = newConfiguracao;
    
        repository.whrite(_json);
      }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search