简体   繁体   English

Flutter:我如何制作消息列表?

[英]Flutter: How i can make List for messages?

I need to make a list of messages, I have this model我需要列出消息,我有这个 model

enum MessageType {sent, received}
class Messages {
  MessageType status;
  String contactName;
  String message;
  String time;

  Messages({ this.status, this.message, this.contactName, this.time});
}

And this way to make a list而这种方式来制作清单

 final response = await http.get(url);

    if(response.statusCode == 200){
      print(response.body);

      var allMessages = (json.decode(response.body) as Map)['messages'] as Map<String, dynamic>;

      var MessagesList = List<Messages>();

      allMessages.forEach((String key, dynamic val){
        var record = Messages(contactName: val['ownerName'], message: val['body'], time: '123', status: );
      });

I have two questions.我有两个问题。

  1. How can I substitute the value 'received' in status?如何替换状态中的“收到”值?

2.how to set received or sent depending on which id? 2.如何根据哪个id设置接收或发送?

If id = 1, then put 'received', if other then put 'sent'如果 id = 1,则输入 'received',否则输入 'sent'

You should be able to just use an inline ternary operator like this: testCondition? trueValue: falseValue您应该能够像这样使用内联三元运算符: testCondition? trueValue: falseValue testCondition? trueValue: falseValue

implemented in your code would look like this:在您的代码中实现如下所示:

allMessages.forEach((String key, dynamic val){var record = Messages(
    contactName: val['ownerName'], 
    message: val['body'], 
    time: '123', 
    status: id==1 ? MessageType.received : MessageType.sent);
});

Hope this helps!希望这可以帮助!

You should do something like this.你应该做这样的事情。 Convert your JSON to a List of Message using a custom "fromJson" method and, during the conversion, set the MessageType as needed.使用自定义“fromJson”方法将您的 JSON 转换为消息列表,并在转换期间根据需要设置 MessageType。

enum MessageType { sent, received }

class Message {
  MessageType status;
  String contactName;
  String message;
  String time;

  Message({this.status, this.message, this.contactName, this.time});

  factory Message.fromJson(Map<String, dynamic> json) => Message(
        status: json["status"] == 1 ? MessageType.received : MessageType.sent,
        contactName: json["contactName"],
        message: json["message"],
        time: json["time"],
      );
}

Future<List<Message>> getMessage() async {
  final response = await http.get(url);

  if (response.statusCode == 200) {
    print(response.body);

    List<Message> allMessages = List<Message>.from(
        json.decode(response.body).map((x) => Message.fromJson(x)));

    return allMessages;
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM