【问题标题】:Group by multiple fields and get max value using Dart and Flutter按多个字段分组并使用 Dart 和 Flutter 获取最大值
【发布时间】:2021-12-11 21:58:18
【问题描述】:

我是飞镖新手,我需要按多个字段分组并获得每个学生的最小值。我不知道如何实施,因为我是飞镖新手。以下是实时 Firebase 表结构的示例。

"gameRanking" : {
    "-MmvcDgrGsuCjhcsmXfP" : {
      "game" : "Puzzle",
      "score" : "105",
      "student" : "John Doe",   
    },
    "-MasdDgrGsuCjhcsmXfP" : {
      "game" : "Puzzle",
      "score" : "99",
      "student" : "John Doe",      
    },
    "-Mmw0kagqLrEbdWlkXg7" : {
      "game" : "Puzzle",
      "score" : "87",
      "student" : "Mary Doe",
    },
    "-MmwC8ONbJUWzP_Wa7X0" : {
      "game" : "Puzzle",
      "score" : "95",
      "student" : "Mary Doe",
    }
  },

这是预期的输出:

Puzzle John Doe  99
Puzzle Mary Doe  87 

【问题讨论】:

  • 嗨,欢迎来到 SO。为了更容易帮助您,请包含您已经尝试过的代码,即使它不起作用(只需指出它不起作用的地方)。这样会更容易提供帮助。
  • 如果你完全不知道,先看看这个答案:stackoverflow.com/questions/54029370/…
  • 你好@Renato,我还没有代码,因为我正在探索dart和flutter。
  • 好的,但是你可能应该先花一些精力学习基础知识......了解Map,具体来说,如何在 Dart 中工作......然后你应该能够提出更有意义的问题.
  • 我已经看过你提到的链接,但它不适合我的需要。

标签: flutter dart flutter-dependencies dart-null-safety


【解决方案1】:

我不会完全回答这个问题,因为这显然是一个“做我的功课”之类的问题。

但为了帮助您开始编程,我认为在此处发布“几乎”整个解决方案会很有用。我希望您随后能够阅读其他相关问题的答案,例如this one,以获得最终解决方案。

给你,这解决了问题的“管道”部分:

class Stats {
  String game;
  int score;
  String student;
  Stats(this.game, this.score, this.student);
  @override
  String toString() => "Stats($game, $score, $student)";
}

main() {
  final map = {
    "gameRanking": {
      "-MmvcDgrGsuCjhcsmXfP": {
        "game": "Puzzle",
        "score": "105",
        "student": "John Doe",
      },
      "-MasdDgrGsuCjhcsmXfP": {
        "game": "Puzzle",
        "score": "99",
        "student": "John Doe",
      },
      "-Mmw0kagqLrEbdWlkXg7": {
        "game": "Puzzle",
        "score": "87",
        "student": "Mary Doe",
      },
      "-MmwC8ONbJUWzP_Wa7X0": {
        "game": "Puzzle",
        "score": "95",
        "student": "Mary Doe",
      }
    },
  };

  final rankingsById = map["gameRanking"] ?? {};

  final rankings = rankingsById.map((id, data) {
    return MapEntry(
        id,
        Stats(data["game"].coerceToString(), data["score"].coerceToInt(),
            data["student"].coerceToString()));
  }).values;

  rankings.forEach((stats) => print(stats));
}

extension on Object? {
  int coerceToInt() => int.parse(coerceToString());

  String coerceToString() => this?.toString() ?? "?";
}

运行此打印:

Stats(Puzzle, 105, John Doe)
Stats(Puzzle, 99, John Doe)
Stats(Puzzle, 87, Mary Doe)
Stats(Puzzle, 95, Mary Doe)

祝你好运完成剩下的猫头鹰:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-07
    • 1970-01-01
    • 2021-02-03
    • 2018-11-28
    • 1970-01-01
    • 1970-01-01
    • 2023-02-04
    相关资源
    最近更新 更多