在 dart 列表的开头插入元素 [英] Insert element at the beginning of the list in dart

查看:28
本文介绍了在 dart 列表的开头插入元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am just creating a simple ToDo App in Flutter. I am managing all the todo tasks on the list. I want to add any new todo tasks at the beginning of the list. I am able to use this workaround kind of thing to achieve that. Is there any better way to do this?

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);
  }

推荐答案

使用Listinsert()方法添加item,这里的index为0 将其添加到开头.示例:

Use insert() method of List to add the item, here the index would be 0 to add it in the beginning. Example:

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

这篇关于在 dart 列表的开头插入元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆