Json 颤振持久性:如何编写列表<;动态>;列出<;类别类型>;?

Json 颤振持久性:如何编写列表<;动态>;列出<;类别类型>;?,json,flutter,asynchronous,serialization,persistence,Json,Flutter,Asynchronous,Serialization,Persistence,我有一个任务类的待办事项列表应用程序。 我想用jsonEncode序列化一个任务列表,并将它们保存到docsdir中的一个文件中。 之后,我希望能够重新序列化相同的列表,并将它们转换为我的本地列表数据类型(从jsonDecode获得的列表)。最好的方法是什么 目前,我尝试: void reSerializeTaskList() async { final directory = await getApplicationDocumentsDirectory(); File f =

我有一个任务类的待办事项列表应用程序。 我想用jsonEncode序列化一个任务列表,并将它们保存到docsdir中的一个文件中。 之后,我希望能够重新序列化相同的列表,并将它们转换为我的本地列表数据类型(从jsonDecode获得的列表)。最好的方法是什么

目前,我尝试:

void reSerializeTaskList() async {
    final directory = await getApplicationDocumentsDirectory();
    File f = File('${directory.path}/new.txt');
    String fileContent = await f.readAsString();
    List<dynamic> jsonList = jsonDecode(fileContent).cast<Task>(); // does not  work
    print("JSONSTRING: ${jsonList.runtimeType}");
    print("$jsonList");
  }

I/flutter (29177): JSONSTRING: CastList<dynamic, Task>
E/flutter (29177): [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Task' in type cast
void reSerializeTaskList()异步{
最终目录=等待getApplicationDocumentsDirectory();
文件f=File('${directory.path}/new.txt');
字符串fileContent=wait f.readAsString();
List jsonList=jsonDecode(fileContent).cast();//不起作用
打印(“JSONSTRING:${jsonList.runtimeType}”);
打印($jsonList);
}
I/颤振(29177):JSONSTRING:CastList
E/flatter(29177):[错误:flatter/lib/ui/ui\u dart\u state.cc(177)]未处理的异常:类型“\u InternalLinkedHashMap”不是类型转换中类型“Task”的子类型
我的解决方法是迭代所有数组元素,并使用Task类中的“fromJson”方法从值中构建任务类型:

  void reSerializeTaskList() async {
    final directory = await getApplicationDocumentsDirectory();
    File f = File('${directory.path}/new.txt');
    String fileContent = await f.readAsString();
    List<dynamic> jsonList = jsonDecode(fileContent);

    List<Task> taskList = [];
    for (var t in jsonList) {
      print("T: $t and ${t.runtimeType}");
      Task task = new Task();
      taskList.add(task.fromJson(t));
    }
    print("JSONSTRING: ${jsonList.runtimeType}");
    print("$jsonList");

    print("$taskList");
    print("$taskList.runtimeType");
  } 
import 'dart:io';

class Task {
  String name;
  bool isDone;

  Task({this.name, this.isDone = false});

  void toggleDone() {
    isDone = !isDone;
  }

  @override
  String toString() {
    // TODO: implement toString
    return "${this.name} is done: $isDone";
  }

  Map<String, dynamic> toJson() {
    return {
      "name": this.name,
      "isDone": this.isDone,
    };
  }

  Task fromJson(Map<String, dynamic> json) {
    this.name = json['name'];
    this.isDone = json['isDone'];
    return this;
  }
}
void reSerializeTaskList()异步{
最终目录=等待getApplicationDocumentsDirectory();
文件f=File('${directory.path}/new.txt');
字符串fileContent=wait f.readAsString();
List jsonList=jsonDecode(fileContent);
列表任务列表=[];
for(jsonList中的var t){
打印(“T:$T和${T.runtimeType}”);
任务=新任务();
taskList.add(task.fromJson(t));
}
打印(“JSONSTRING:${jsonList.runtimeType}”);
打印($jsonList);
打印(“$taskList”);
打印(“$taskList.runtimeType”);
} 
我的任务类:

  void reSerializeTaskList() async {
    final directory = await getApplicationDocumentsDirectory();
    File f = File('${directory.path}/new.txt');
    String fileContent = await f.readAsString();
    List<dynamic> jsonList = jsonDecode(fileContent);

    List<Task> taskList = [];
    for (var t in jsonList) {
      print("T: $t and ${t.runtimeType}");
      Task task = new Task();
      taskList.add(task.fromJson(t));
    }
    print("JSONSTRING: ${jsonList.runtimeType}");
    print("$jsonList");

    print("$taskList");
    print("$taskList.runtimeType");
  } 
import 'dart:io';

class Task {
  String name;
  bool isDone;

  Task({this.name, this.isDone = false});

  void toggleDone() {
    isDone = !isDone;
  }

  @override
  String toString() {
    // TODO: implement toString
    return "${this.name} is done: $isDone";
  }

  Map<String, dynamic> toJson() {
    return {
      "name": this.name,
      "isDone": this.isDone,
    };
  }

  Task fromJson(Map<String, dynamic> json) {
    this.name = json['name'];
    this.isDone = json['isDone'];
    return this;
  }
}
导入'dart:io';
课堂任务{
字符串名;
布尔伊斯通;
任务({this.name,this.isDone=false});
void toggleDone(){
isDone=!isDone;
}
@凌驾
字符串toString(){
//TODO:实现toString
返回“${this.name}已完成:$isDone”;
}
映射到JSON(){
返回{
“名字”:这个名字,
“isDone”:这个,
};
}
任务fromJson(映射json){
this.name=json['name'];
this.isDone=json['isDone'];
归还这个;
}
}

但是有没有其他更好的方法呢?这在我看来很不完善…

举个小例子,我就是这样做的

final jsonResponse=json.decode(jsonString);
最终列表customers=jsonResponse.map((jR)=>Customer.fromJson(jR)).toList();
Customer类中的fromJson如下所示

factory Customer.fromJson(映射json)=>Customer(
id:json[“id”]==null?null:json[“id”],
changeDate:json[“changeDate”]==null?null:DateTime.parse(json[“changeDate”]),
name:json[“name”]==null?null:json[“name”],
);

谢谢,这样做很有效,而且看起来更好,但是我的方法'Task fromJson(Map json)`和你的方法
factory Task.fromJson…
有什么区别呢?我还不太了解这种语法..工厂避免创建新实例。我想我也像你们一开始那样做了,但因为所有的例子都使用了工厂,我就换了(所以我个人没有经历过负面影响)。May main point是第一个带有
.map
的片段,当它回答您的问题时,接受答案将是一个很好的手势:-)