iamnull90
iamnull90

Reputation: 79

Flutter list view rendering issue

I'm currently working through learning Flutter. I'm starting with trying to build the basic list app. The current flow I have is my Stateful TasksManager Widget saving user input to the state, and then pushing it to the _taskList List, which I have being sent over to a Stateless TaskList widget, which is rendering the list.

I expect the list view to be updated with the new task after the "Save" button is clicked, but what I'm getting is after I "Save", the list view only updates during the subsequent change of state. For example, if I were to "Save" the string "Foo" to add to the list, I'm only seeing that update in the view after I go to type in another item, such as "Bar".

TaskManager

class TasksManager extends StatefulWidget{
@override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return TasksManagerState();
  }

}

class TasksManagerState extends State<TasksManager>{

  final List _taskList = [];
  String _newTask = '';


  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Column(
      children: <Widget>[
        TextField(
          onChanged: (value){
            setState(() {
              _newTask = value;
            });
            print(_taskList);
          },
        ),
        RaisedButton(
          child: Text('Save'),
          onPressed: () => _taskList.add(_newTask),
        ),
        Expanded(child: TaskList(_taskList))
      ],
    );
  }

} 

TaskList

class TaskList extends StatelessWidget {
  final List taskList;

  TaskList(this.taskList);

  Widget _buildListItem(BuildContext context, int index) {
    return ListTile(
      title: Text(taskList[index]),
    );
  }


  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return ListView.builder(
      itemBuilder: _buildListItem,
      itemCount: taskList.length,
    );
  }
} 

Upvotes: 1

Views: 954

Answers (1)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 658255

Yes, Flutter only updates when it is instructed to. setState() marks the widget dirty and causes Flutter to rebuild:

onPressed: () => setState(() => _taskList.add(_newTask)),

Upvotes: 2

Related Questions