Search code examples
listviewflutterdartsetstate

Flutter ListView with widgets in a List doesn't updates when it should


I am trying to store Widgets to build by a ListView in a global List like this:

List<Widget> globalList= [];

Im trying to build a Listview in the state of a stateful class like this:

ListView(
  children: globalList
)

Now im trying to render this Listview everytime, when an item is added to the list. The function i use for this is:

void addList(){
    setState((){
      Widget _widget = new Widget();
      list.add(_widget);
    });

The Widget (in my pseudocode called _widget) is also a Stateful widget. But when i call addList, my stateful widget does not update. Why?

Shortended (Pseudo)-Code:

List<Widget> globalList = [];

class STFUL extends StatefulWidget{

  @override
  _STFULState createState() => _STFULState();
}

class _STFULState extends State<STFUL>{
  void addList(){
    setState((){
      Widget _widget = new Widget();
      globalList.add(_widget);
      });
@override
Widget build(BuildContext context) {
  return Scaffold(
    body:ListView(
      children: globalList
    )
  }  
} 

Below there is a button to call addList. My problem is, that the ListView doesn't renders the updated list, when I call setState.

Thank you for your help


Solution

  • use ListView.Builder in place of your ListView,