gpt4 book ai didi

dart - 将 http 响应转换为 Flutter 列表

转载 作者:IT王子 更新时间:2023-10-29 07:09:37 26 4
gpt4 key购买 nike

我在将 HTTP 响应正文转换为 Flutter 列表时遇到问题。在调试器中,jsonDecode(response.body)['data']['logsread'] 的输出看起来完全像

[
{
"id": "9fd66092-1f7c-4e60-ab8f-5cf7e7a2dd3b",
"email": "email@gmail.com"
}
]

但是,这会返回 false。

print((jsonDecode(response.body)['data']['logsread']) ==
[{
"id": "9fd66092-1f7c-4e60-ab8f-5cf7e7a2dd3b",
"email": "email@gmail.com"
}]); // This returns false.

仅供引用。响应体 =>

"{"data":{"logsread":[{"id":"9fd66092-1f7c-4e60-ab8f-5cf7e7a2dd3b","email":"email@gmail.com"}]}}"

最佳答案

JsonDecode 返回 List 但您的另一个列表的类型为 List >。因此,通过创建任何模型并覆盖 == 和哈希码,将其转换为相同类型的列表。

要比较两个列表,您需要 ListEquality 函数。示例:

    Function eq = const ListEquality().equals;
print(eq(list1,list2));

我试过你的代码并按照我的方式完成,检查是否可行。

模型类:

    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;

}

主.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));

希望这就是您要找的。

关于dart - 将 http 响应转换为 Flutter 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54684990/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com