首页 > 解决方案 > 如何在颤动中比较一串键/值中的两个值?

问题描述

您好,我尝试检测字符串中的两个键之间是否具有相同的值

我有这样的格式

[
{array: id: idX, vote: X, description: textX}, 
{array: id: idX, vote: X, description: textX}
]

我会找到一个解决方案来确定有最佳投票的情况和有平等投票的情况


案例1有赢家:

[
{array: id: id1, vote: 2, description: text1}, 
{array: id: id2, vote: 1, description: text2}
]

id1 = win => 显示 text1


案例2没有赢家:

[
{array: id: id1, vote: 2, description: text1}, 
{array: id: id2, vote: 2, description: text2}
]

id 1 & 2 = 相等 => 等待消息

标签: flutter

解决方案


您输入的数据类型是什么?你提到它是字符串,但我可以看到它是地图列表。

// your data
List<Map<String, dynamic>> data = [];

// here assuming vote will be always greater than 0
// therefore setting maxVote = -1
int maxVote = -1;
String displayText = "";

// starting from second element
for(int i=1; i< data.length; i++){
  if(data[i]['vote'] > data[i-1]['vote']){
    maxVote = data[i]['vote'];
    displayText = data[i]['description'];
  }
  if(data[i]['vote'] < data[i-1]['vote']){
    maxVote = data[i-1]['vote'];
    displayText = data[i-1]['description'];
  }
}

if(maxVote == -1){
  // all votes where equal
  print("wait message");
}else{
  print(displayText);
}

推荐阅读