我在将 HTTP 响应正文转换为 Flutter 列表时遇到问题。在调试器中,输出jsonDecode(response.body)['data']['logsread']看起来完全像
[
{
"id": "9fd66092-1f7c-4e60-ab8f-5cf7e7a2dd3b",
"email": "email@gmail.com"
}
]
Run Code Online (Sandbox Code Playgroud)
然而,这返回错误。
print((jsonDecode(response.body)['data']['logsread']) ==
[{
"id": "9fd66092-1f7c-4e60-ab8f-5cf7e7a2dd3b",
"email": "email@gmail.com"
}]); // This returns false.
Run Code Online (Sandbox Code Playgroud)
供参考。响应.body =>
"{"data":{"logsread":[{"id":"9fd66092-1f7c-4e60-ab8f-5cf7e7a2dd3b","email":"email@gmail.com"}]}}"
Run Code Online (Sandbox Code Playgroud)
小智 4
JsonDecode 返回 List<dynamic> 但您的另一个列表的类型为 List<Map<String,String>>。因此,通过创建任何模型并覆盖 == 和哈希码,将其转换为相同类型的列表。
要比较两个列表,您需要 ListEquality 函数。例子 :
Function eq = const ListEquality().equals;
print(eq(list1,list2));
Run Code Online (Sandbox Code Playgroud)
我尝试了你的代码并按照我的方式完成了,检查是否可以。
型号类别:
class Model {
String id;
String email;
Model({
this.id,
this.email,
});
factory Model.fromJson(Map<String, dynamic> json) => new Model(
id: json["id"],
email: json["email"],
);
Map<String, dynamic> toJson() => {
"id": id,
"email": email,
};
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is Model &&
runtimeType == other.runtimeType &&
id == other.id &&
email == other.email;
@override
int get hashCode =>
id.hashCode ^
email.hashCode;
}
Run Code Online (Sandbox Code Playgroud)
主程序.dart
import 'package:collection/collection.dart';
var body =
'{"data":{"logsread":[{"id":"9fd66092-1f7c-4e60-ab8f-5cf7e7a2dd3b","email":"email@gmail.com"}]}}';
var test1 = (jsonDecode(body)['data']['logsread'] as List)
.map((value) => Model.fromJson(value))
.toList();
var test2 = ([
{"id": "9fd66092-1f7c-4e60-ab8f-5cf7e7a2dd3b", "email": "email@gmail.com"}
]).map((value)=>Model.fromJson(value)).toList();
Function eq = const ListEquality().equals;
print(eq(test1,test2));
Run Code Online (Sandbox Code Playgroud)
我希望这就是您正在寻找的。
| 归档时间: |
|
| 查看次数: |
8356 次 |
| 最近记录: |