How to update UI when adding new items to ListView

Currently I am using a column to display a list of items on the screen, but as soon as the list gets to large it can´t be displayed anymore. That´s why I wanna use a ListView instead of a column. I use a button to add a new “card” to the list and with setState I rebuild everything to display the new added card. That works fine with the column.

My problem: When I implement the ListView instead of a column the item I add to the list with the “add-button” will get added to the list, but the UI wont update and new item wont be displayed on screen.

//Here I use a column, but I don´t know how to implent a ListView
//to get the same result/functionality

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}




class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  MyToDoCards myToDoCardsList = MyToDoCards();

  void addNewContainer() {
    setState(() {
      myToDoCardsList.toDoCards.add(
        Container(
          margin: EdgeInsets.only(top: 15.0),
          height: MediaQuery.of(context).size.height * 0.05,
          color: Colors.blue,
        ),);
    });
    print(myToDoCardsList.toDoCards);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      bottomNavigationBar: BottomAppBar(
        child: Container(
          height: 50.0,
        ),
      ),
      body: Center(
        child: Container(
          width: MediaQuery.of(context).size.width * 0.8,
          child: Column(
            children: myToDoCardsList.toDoCards,
          )
        ),
      ),
      floatingActionButton: FloatingActionButton(
        backgroundColor: Colors.yellow,
        onPressed: () {addNewContainer();},
        child: Icon(
          Icons.add,
          color: Colors.black,
        ),
      ),
      floatingActionButtonLocation: 
FloatingActionButtonLocation.centerDocked,
    );
  }
}

class MyToDoCards {

  List<Widget> toDoCards = [
    Container(
      margin: EdgeInsets.only(top: 15.0),
      height: 40.0,
      color: Colors.blue,
    ),
  ];
}

It looks like that there is no ListView widget in your code. Maybe you need to heck it again.

2 Likes