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

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

问题描述

我只是在Flutter中创建一个简单的ToDo应用。我正在管理列表中的所有待办事项。我想在列表的开头添加任何新的待办事项。我能够使用这种解决方法来实现这一目标。有什么更好的方法吗?

I am just creating a simple ToDo App in Flutter. I am managing all the todo tasks in the list. I want to add any new todo task 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);
  }


推荐答案

使用 List 的> insert()方法添加项,此处索引为 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天全站免登陆