skip to Main Content

In my app, i created ListView list of widgets, but when i try to update it via list it doesn’t update

Example Code:

import 'package:flutter/material.dart';

class ListTest extends StatefulWidget {
  const ListTest({Key? key}) : super(key: key);

  @override
  State<ListTest> createState() => _ListTestState();
}

class _ListTestState extends State<ListTest> {
  List<Widget> widget_list = [
    ListTile(title: Text("1"),),
    ListTile(title: Text("2"),),
    ListTile(title: Text("3"),),
  ];
  @override
  Widget build(BuildContext context) {
    print("List Length: "+widget_list.length.toString());
    return Scaffold(
      appBar: AppBar(
        title: Text("List Test"),
      ),
      body: ListView(
        children: widget_list,
      ),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.delete),
        onPressed: (){
          widget_list.clear();
          setState(() {});
        },
      ),
    );
  }
}

Here when page is opened list length is 3, and when setState is called list length 0 is printed, but ListView doesn’t get updated.

2

Answers


  1. You can solve this problem by using ListView.builder instead of ListView. With the itemCount you give to ListView.builder, the number of elements of the list becomes dynamic. When there is a change in the number of elements, the list number is updated again.

    ListView.builder(
        itemCount: widget_list.length,
        itemBuilder: (context, index) {
          return ListTile(
            title: widget_list[index],
          );
        },
      ),
    
    Login or Signup to reply.
  2. I believe what happens is that on rebuild the ListView sees that it is the same List object so it thinks that it doesn’t need to be rebuild. To make it work correctly you can do

        onPressed: (){
          widget_list.clear();
          widget_list = widget_list.toList();
          setState(() {});
        },
    

    That way it actually will be a different List object.

    In the documentation of ListView it also says:

      /// Like other widgets in the framework, this widget expects that
      /// the [children] list will not be mutated after it has been passed in here.
    

    Or you can also use a ListView.builder instead like in hakandl’s answer.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search