Error with Map<String, Dynamic> - Cannot recognize String as Dynamic

Asked

Viewed 1,221 times

-1

I have the following Flutter error:

type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'String'

This error is occurring when I have run the code seginte:

  List _listaTarefas = [];
  _salvarArquivo() async{

        final diretorio = await getApplicationDocumentsDirectory();
        var arquivo =  File("${diretorio.path}/dados.json" );

        Map<String, dynamic> tarefa = Map();
        tarefa["titulo"] = "Ir ao Mercado";
        tarefa["realizada"] = false;
        _listaTarefas.add(tarefa);

        String dados = json.encode(_listaTarefas);
        arquivo.writeAsString(dados);

  }
  • Guys, I figured out the problem: ;List _listaTarefas = []; must be List<dynamic> _listaTarefas = []; .

1 answer

1

Even if you have already found a solution to your problem, I will also leave here a proposal to improve your code, and maintain a clean architecture, so that it is easier for you to understand what you are writing:

If you have a task list, and the type that will be inserted in this list is always a Map<String, dynamic>, now you better set the list as:

List<Map<String, dynamic>> _listaTarefas = [];

Thus, only Map with that format can be inserted, but ok, we already understood, by the variable name, that this is a task list, but how is a task formed? What values can they have? How can I remember these values in 1 week, 1 month, without having to search for a task file to know how it is structured? Luckily, is a language typified and Object-Oriented, now how about we make a class that represents a structure of a task:

class Tarefa{
  String titulo;
  bool realizada;

  Tarefa(this.titulo, this.realizada);

  Map<String, dynamic> get toMap => {
    'titulo': titulo,
    'realizada': realizada
  }

  String get toJsonString => json.encode(this.toMap);
}

And now we can change the list to:

List<Tarefa> _listaTarefas = [];

And with that your method _salvarArquivo can be simplified in this way:

_salvarArquivo() async{
  final diretorio = await getApplicationDocumentsDirectory();
  var arquivo =  File("${diretorio.path}/dados.json" );

  Tarefa tarefa = Tarefa("Ir ao Mercado", false);
  _listaTarefas.add(tarefa);
  arquivo.writeAsString(tarefa.toJsonString);
}

If you have a class with many attributes, Json Serialization can simplify your life by generating most of the conversion code between objects for you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.