簡體   English   中英

如何從 dart flutter 中的鍵或鍵值對獲取索引

[英]How to get index from key or key value pair in dart flutter

我有一個鍵值對列表

我想從鍵中搜索索引(在鍵 == 0 的列表中獲取索引),然后從該索引中我想更改值。

或者將值更改為 key == 1

void main() {
  var listAnswers = [];
  var keyPair = {
    'Key': 0,
    'value': false,
  };

  listAnswers.add(keyPair);

  keyPair = {
    'Key': 1,
    'value': 1,
  };

  listAnswers.add(keyPair);

  keyPair = {
    'Key': 2,
    'value': DateTime.now(),
  };

  listAnswers.add(keyPair);

  print(listAnswers);

  var index = listAnswers.getIndex('key', 0)
  // got the index 1 (where key = 0, and value = false)

  listAnswers[i].value = true; // then I want to do something like this.

}

  var index = listAnswers.indexWhere((pair) => pair['Key'] == 0);
      print(index);
      
     listAnswers[index]['value'] = true;

您已經這樣聲明keyPair

var keyPair = {
    'Key': 0,
    'value': false,
  };

這里的keyPairMap

要訪問 map 中的密鑰,您必須使用keyPair['Key']

現在,當您將這個 map 添加到一個列表中時,您就有了一個地圖列表。

獲取key為0的map的索引。

var index = listAnswers.indexWhere((map) => map['Key'] == 0);

現在更改該索引處的值。

// listAnswers[index] returns a map
// to access the 'value' you need to use listAnswers[index]['value']
listAnswers[index]['value'] = true;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM