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, Dart 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.
Guys, I figured out the problem: ;
List _listaTarefas = [];
must beList<dynamic> _listaTarefas = [];
.– João Dutra