在 dart 中在列表的开头插入元素

Rop*_*shi 66 list insert dart flutter

我只是在 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);
  }
Run Code Online (Sandbox Code Playgroud)

Cop*_*oad 132

使用insert()方法List添加项目,这里的索引是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"]
Run Code Online (Sandbox Code Playgroud)


小智 14

List.insert(index, value);
Run Code Online (Sandbox Code Playgroud)


小智 14

我想添加另一种方法来在列表的开头附加元素,如下所示

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

//prints [0, 1, 2, 3]
Run Code Online (Sandbox Code Playgroud)

  • 是的,也可以合并两个列表。[...列表1,...列表2] (2认同)

Elm*_*mar 10

将新项目添加到列表的开头和结尾:

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"];
Run Code Online (Sandbox Code Playgroud)


nat*_*ech 7

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

// Given
List<int> list = [2, 3, 4];
Run Code Online (Sandbox Code Playgroud)
list = [
  1,
  for (int item in list) item,
];
Run Code Online (Sandbox Code Playgroud)

或者

list = [
  1,
  ...list,
];
Run Code Online (Sandbox Code Playgroud)

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