Flutter unable to set state of list<object>

Here is how the main TodoApp widget looks like:

class TodoApp extends StatelessWidget {
  Widget build(BuildContext context) {
    return new MaterialApp(title: 'Todo List', home: new TodoList());

I have created a class for a list item which is called Task:

class Task {
  String name;
  int number;

  Task(this.name, this.number);

The list widget looks like this:

class TodoList extends StatefulWidget {
  createState() => new TodoListState();

The TodoListState class has a method which adds new items to the list:

class TodoListState extends State<TodoList> {
  List<Task> _todoItems = [];
  List<bool> checkedItems = []; // this was created for testing purposes

  void _addTodoItem(Task task) {
    if (task.name.length > 0) {
      setState(() => checkedItems.add(false)); // works fine
      setState(() => _todoItems.add(new Task('abc', 12))); // does not work

Why when _addTodoItem method is called, one item is added to the checkedItems list but _todoItems list is left unchanged? What am I missing?

1 answer

  • answered 2019-05-21 20:08 Haroun Hajem

    It's working as it should, setState is only called once, hence the first method is executed. You should add both methods in the setState method, since it's called once per run or state, you can write it like this:

     setState(() => {  
          _todoItems.add(new Task('abc', 12);