【问题标题】:Flutter; replace item in list扑;替换列表中的项目
【发布时间】:2021-03-06 17:21:04
【问题描述】:

我的应用中有一个列表。它包含几个项目。

我想用另一个用户输入(另一个字符串)替换每个等于用户输入(一个字符串)的项目。 (如果解决方案是删除该项目,并添加一个新项目,它需要在列表中的相同位置)

我该怎么做?

谢谢:)

【问题讨论】:

    标签: list flutter dart


    【解决方案1】:

    您也可以为此使用 replaceRange

    void main() {
      var list = ['Me', 'You', 'Them'];
      print(list); // [Me, You, Them]
      var selected = 'You'; // user input A (find)
      var newValue = 'Yours'; // user input B (replace)
      
      // find the item you want to replace, in this case, it's the value of `selected`.
      var index = list.indexOf(selected);
      
      // if replacing only one item, the end index should always be `startIndex` +1.
      // `replaceRange` only accepts iterable(list) so `newValue` is inside the array.
      list.replaceRange(index, index + 1, [newValue]);
      
      print(list); // [Me, Yours, Them]
    }
    

    【讨论】:

      【解决方案2】:
      for (int i = 0; i < LIST.length; i++){
          if (LIST[i] == USERINPUT1){
              LIST[i] = USERINPUT2;
          }
      }
      

      基本上在应用中遍历列表,检查输入是否等于用户输入。

      index = LIST.indexOf(USERINPUT1);
      
      if (index != -1){
          LIST[index] = USERINPUT2;
      }
      

      这仅适用于第一次出现。

      【讨论】:

        【解决方案3】:

        我会这样做:

        void main() {
          String inputString = 'myInput'; // User input to replace inside the list
          List<String> list = ['1', inputString, '3', '4', '5', inputString, '7']; // List of items
          List<String> filteredList = list.where((e) => e == inputString).toList();
          for (final e in filteredList) {
            final index = list.indexOf(e);
            list.removeAt(index);
            list.insert(index, 'newInput'); // Replacing inputString by 'newInput'
          }
        }
        

        基本上我正在做的是创建一个子列表filteredList,只包含用户输入的出现。然后我遍历我的filteredList,在从list 中删除项目之前,我保留它的索引以在正确的位置插入我的新元素。

        Try the code on DartPad

        【讨论】:

          猜你喜欢
          • 2021-06-13
          • 2019-12-02
          • 2012-11-11
          • 1970-01-01
          • 1970-01-01
          • 2010-09-15
          • 2019-02-21
          • 2021-10-14
          • 1970-01-01
          相关资源
          最近更新 更多