【问题标题】:Flutter How to append a groupedBy to a List?Flutter 如何将 groupedBy 附加到列表中?
【发布时间】:2021-08-14 21:58:44
【问题描述】:

我是 Flutter 的新手,所以如果我需要添加任何其他上下文,请告诉我。

我的应用中有一个标签,我需要在其中显示一个列表。该列表将是单个项目和项目组的组合。

所以一个例子是:

  • 第 1 项 -- 欢迎使用此应用程序!哈哈哈哈哈哈
  • 第 2 项 -- 用户 A 和用户 B 刚刚赞了您的帖子!
  • 第 3 项 -- 用户 A、用户 B 和其他 15 人回复了您的帖子!

所以这个列表将有两个不同的项目,一个是通用类型,一个是分组类型。

这些组将有自己的类型,这就是我对它们进行分组的方式。在此示例中,它将按喜欢帖子或通过回复帖子来分组。

在我的分组结束时,这就是我所拥有的:

// postLikes
MapEntry(PostType.postLikes: [Post{test, test, testID1, testId2, PostType.postLikes}, Post{test, test, testID1, testID2, PostType.postLikes}])

// postReplies
MapEntry(PostType.postReplies: [Post{test, test, testID1, testID2, PostType.postReplies}])

如果我这样做:

var groupedPosts = <Post>[];
groupedPosts.addAll(groupedPostsByType.value);

然后它们都被添加但分组被分开。

如果还有什么可以帮助的,请告诉我。

【问题讨论】:

  • 演示您遇到的问题的完整示例将有很大帮助。它还有助于显示您获得的输出以及您想要的输出。

标签: list flutter group-by


【解决方案1】:

据我了解您的问题,

enum PostType { normal, like, reply }

class Post {
  final PostType type;
  final DateTime time;
  final String message;
  final List<User> users;

  String get formattedUser {
    if (users == null) return "";
    if (users.length > 2)
      return "${users.first} and ${users.length - 1} others";
    return users.join(" and ");
  }

  String get formattedMessage {
    switch (type) {
      case PostType.normal:
        return message;
      case PostType.like:
        return "$formattedUser liked your post.";
      case PostType.reply:
        return "$formattedUser replied to your post.";
      default:
        return "n/a"; //replace with your default message
    }
  }

  Post({this.type, this.time, this.message, this.users});
}

class User {
  final String name;
  final String otherField;

  User(this.name, [this.otherField]);

  @override
  String toString() => this.name;
}

void main() {
  var data = [
    Post(type: PostType.normal, message: "Welcome to something!"),
    Post(type: PostType.like, users: [
      User("Mr. X"),
      User("Mr. Y"),
    ]),
    Post(type: PostType.reply, users: [
      User("Mr. A"),
      User("Mr. B"),
      User("Mr. C"),
      User("Mr. D"),
    ])
  ];

  data.forEach((element) {
    print(element.formattedMessage);
  });
  
  //TODO: In order to group the data based on their type
  var messages = data.where((element) => element.type == PostType.normal);
  var likes = data.where((element) => element.type == PostType.like);
  var replies = data.where((element) => element.type == PostType.reply);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-06
    • 2018-04-25
    • 2020-06-30
    • 2021-08-11
    • 2011-12-09
    • 1970-01-01
    • 2013-12-24
    • 2021-11-14
    相关资源
    最近更新 更多