gpt4 book ai didi

dart - For Each 循环在 dart 中创建数组

转载 作者:IT王子 更新时间:2023-10-29 07:21:30 25 4
gpt4 key购买 nike

我们需要为每个循环创建一个从 JSON 调用创建数组的循环。我是 flutter 的新手,所以我正在寻找明智地执行此性能的最佳方法。这是目前的现有代码:

这是我们需要通过 JSON 调用循环并创建的数组格式

var ForumPostArr = [
new ForumPostEntry("User1", "2 Days ago", 0 , 0 , "Hello,\n\nLorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."),
new ForumPostEntry("User2", "23 Hours ago", 1 , 0 , "Pellentesque justo metus, finibus porttitor consequat vitae, tincidunt vitae quam. Vestibulum molestie sem diam. Nullam pretium semper tempus. Maecenas lobortis lacus nunc, id lacinia nunc imperdiet tempor. Mauris mi ipsum, finibus consectetur eleifend a, maximus eget lorem. Praesent a magna nibh. In congue sapien sed velit mattis sodales. Nam tempus pulvinar metus, in gravida elit tincidunt in. Curabitur sed sapien commodo, fringilla tortor eu, accumsan est. Proin tincidunt convallis dolor, a faucibus sapien auctor sodales. Duis vitae dapibus metus. Nulla sit amet porta ipsum, posuere tempor tortor.\n\nCurabitur mauris dolor, cursus et mi id, mattis sagittis velit. Duis eleifend mi et ante aliquam elementum. Ut feugiat diam enim, at placerat elit semper vitae. Phasellus vulputate quis ex eu dictum. Cras sapien magna, faucibus at lacus vel, faucibus viverra lorem. Phasellus quis dui tristique, ultricies velit non, cursus lectus. Suspendisse neque nisl, vestibulum non dui in, vulputate placerat elit. Sed at convallis mauris, eu blandit dolor. Vivamus suscipit iaculis erat eu condimentum. Aliquam erat volutpat. Curabitur posuere commodo arcu vel consectetur."),
new ForumPostEntry("User3", "2 Days ago", 5 , 0 , "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."),
new ForumPostEntry("User4", "2 Days ago", 0 , 0 , "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."),
];

这是返回多个答案对象的 JSON 调用

Future<ForumAnswers> getForumAnswers(String postID) async {
final response =
await http.post('/api/ForumAnswers',
headers: {"Content-Type": "application/json",
'Accept': 'application/json',},
body: json.encode({'PostID' : postID }));

if (response.statusCode == 200) {
// If the call to the server was successful, parse the JSON
ForumAnswers _answers;
_answers = ForumAnswers.fromJson(json.decode(response.body));

return _answers;

} else {
// If that call was not successful, throw an error.
throw Exception('Failed to load object');
}

}

最佳答案

这个问题可以使用更多的信息,但已经足够了。有两种方法可以做到这一点——最简单的是使用转换库中的 json 解码器并手动解码。另一种选择是使用 json 序列化库,它在编译时使用代码生成来为您的类创建序列化/反序列化例程。

我不会深入研究代码生成,但这是我手动完成的方式:

import 'dart:convert';

class ForumAnswers {
final List<ForumAnswer> answers;

ForumAnswers(this.answers);

factory ForumAnswers.fromJson(String jsonText) {
return ForumAnswers((json.decode(jsonText) as List).map((item) => ForumAnswer.fromJson((item as Map).cast())).toList());
}

@override
String toString() {
return answers.toString();
}
}

class ForumAnswer {
final String userId;
final DateTime timestamp;
final int views;
final String text;

ForumAnswer({this.userId, this.timestamp, this.views, this.text});

String get daysAgo {
int daysAgo = -timestamp.difference(DateTime.now()).inDays;
if (daysAgo == 1) {
return "1 day ago";
} else {
return "$daysAgo days ago";
}
}

static const String USERID = "userid";
static const String TIMESTAMP = "timestamp";
static const String VIEWS = "views";
static const String TEXT = "text";

factory ForumAnswer.fromJson(Map<String, dynamic> map) {
String userId = map[USERID];
String dateTimeString = map[TIMESTAMP];
int views = map[VIEWS];
String text = map[TEXT];

DateTime dateTime = DateTime.parse(dateTimeString);

return ForumAnswer(userId: userId, timestamp: dateTime, views: views, text: text);
}

@override
String toString() {
return "$runtimeType(userid=$userId, ago=$daysAgo, views=$views, text=$text)";
}
}

void main() {
String json = """
[
{"userid": "User1", "timestamp": "2019-03-24 13:27:00.123456z", "views": 3, "text": "Hello" },
{"userid": "User2", "timestamp": "2019-03-28 13:30:00.234234z", "views": 2, "text": "Hello to you too" },
{"userid": "User1", "timestamp": "2019-03-29 13:42:00.982178z", "views": 1, "text": "Goodbye" }
]
""";

print("Decoded from json: ${ForumAnswers.fromJson(json)}");
}

或者看 in dartpad

虽然您的问题中缺少一些假设...例如,ForumAnswer 和 ForumAnswers 类实际上是关于什么的,您返回的 json 是什么样的,以及 ForumPostEntry 中的参数是什么。但是您应该能够通过此代码进行更改以执行您想要的操作。

我建议阅读 flutter's documentation for json,因为它解释的内容与我的代码所做的基本相同,以及如何使用序列化库。

关于dart - For Each 循环在 dart 中创建数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55401368/

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