通过字符 Flutter 对字符串列表进行排序

问题描述 投票:0回答:1

我有一个字符串列表 ["pana", "open","peno","alp","palp"]

我需要通过字母“p”对它们进行排序,然后按字母顺序:

所以结果应该是 ["pana", "palp","peno", "open","alp"]

我如何在 Flutter 中做到这一点

string flutter list dart sorting
1个回答
0
投票

尝试这样的事情

words.sort((a, b) {
    // Custom comparison function
    if (a.contains('p') && !b.contains('p')) {
      // If a has 'p' and b does not, a comes first
      return -1;
    } else if (!a.contains('p') && b.contains('p')) {
      // If b has 'p' and a does not, b comes first
      return 1;
    } else {
      // If both have 'p' or both don't have 'p', compare alphabetically
      return a.compareTo(b);
    }
  });
© www.soinside.com 2019 - 2024. All rights reserved.