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
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.
I believe what happens is that on rebuild the
ListView
sees that it is the sameList
object so it thinks that it doesn’t need to be rebuild. To make it work correctly you can doThat way it actually will be a different
List
object.In the documentation of
ListView
it also says:Or you can also use a
ListView.builder
instead like in hakandl’s answer.