对于每个循环在dart中创建数组

时间:2019-03-28 15:27:13

标签: dart flutter

我们需要为每个循环创建一个,该循环通过JSON调用创建一个数组。我是新手,所以我正在寻找最佳的方式来实现这种性能。这是截至目前的现有代码:

这是我们需要循环通过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');
  }

}

1 个答案:

答案 0 :(得分:1)

这个问题可能会使用更多的信息,但是有足够的内容可以解决。有两种方法-最简单的方法是使用转换库中的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,因为它与我的代码所做的解释以及使用序列化库的方法基本相同。