Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
262 views
in Technique[技术] by (71.8m points)

flutter - Insert element at the beginning of the list in dart

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);
  }
question from:https://stackoverflow.com/questions/57635916/insert-element-at-the-beginning-of-the-list-in-dart

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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"]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...