【问题标题】:Insert element at the beginning of the list in dart在 dart 列表的开头插入元素
【发布时间】:2019-12-29 08:19:39
【问题描述】:

我只是在 Flutter 中创建一个简单的 ToDo 应用程序。我正在管理列表中的所有待办事项。我想在列表的开头添加任何新的待办事项。我可以使用这种解决方法来实现这一点。有没有更好的方法来做到这一点?

void _addTodoInList(BuildContext context){
    String val = _textFieldController.text;

    final newTodo = {
      "title": val,
      "id": Uuid().v4(),
      "done": false
    };

    final copiedTodos = List.from(_todos);

    _todos.removeRange(0, _todos.length);
    setState(() {
      _todos.addAll([newTodo, ...copiedTodos]);
    });

    Navigator.pop(context);
  }

【问题讨论】:

    标签: list flutter dart insert


    【解决方案1】:

    使用Listinsert()方法添加项目,这里的索引将是0在开头添加它。示例:

    List<String> list = ["B", "C", "D"];
    list.insert(0, "A"); // at index 0 we are adding A
    // list now becomes ["A", "B", "C", "D"]
    

    【讨论】:

      【解决方案2】:

      使用

      List.insert(index, value);
      

      【讨论】:

        【解决方案3】:

        我想在这样的列表开头添加另一种附加元素的方法

         var list=[1,2,3];
         var a=0;
         list=[a,...list];
         print(list);
        
        //prints [0, 1, 2, 3]
        

        【讨论】:

        • yup 也适用于合并两个列表。 [...list1, ...list2]
        【解决方案4】:

        其他答案都很好,但现在 Dart 有一些与 Python 的列表理解非常相似的东西,我想说明一下。

        List<int> list = [2, 3, 4];
        list = [
           1,
           for (int item in list) item,
        ];
        

        结果为 [1, 2, 3, 4]

        【讨论】:

          【解决方案5】:

          在列表的开头和结尾添加一个新项目:

          List<String> myList = ["You", "Can", "Do", "It"];
          myList.insert(0, "Sure"); // adding a new item to the beginning
          
          // new list is: ["Sure", "You", "Can", "Do", "It"];
          
          lastItemIndex = myList.length;
          
          myList.insert(lastItemIndex, "Too"); // adding a new item to the ending
          // new list is: ["You", "Can", "Do", "It", "Too"];
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2018-01-27
            • 2015-01-02
            • 2014-11-15
            • 1970-01-01
            • 2022-01-14
            • 2021-08-16
            • 1970-01-01
            相关资源
            最近更新 更多