Home > Software design >  Show model (class) list in Listview Widget
Show model (class) list in Listview Widget

Time:10-03

Here is a typical flutter example for the ListView of a List. In all cases found on the Internet, the examples assume that you are using a list with only one property (here in the example, child names).

List<String> items = <String>[
  "Eva",
  "Delhi",
  "Adam",
  "Bob",
  "Lara"
];

 ListView.builder(
    shrinkWrap: true,
    itemCount: items.length,
    itemBuilder: (BuildContext context, int index) {
      return Container(
        color: Colors.blue,
        margin: EdgeInsets.all(10),
        padding: EdgeInsets.all(15),
        alignment: Alignment.center,
        child: Text(
          items[index],
          style: TextStyle(
            color: Colors.white,
            fontSize: 22,
          ),
        ),
      );
    }),

But what if I want to show his birthday, birthplace, parents, address, etc. in addition to the child's name?

In C# I basically work with lists that come from models (classes) and have multiple properties. I assume that Flutter programmers work similarly.

How do you proceed if you have e.g. a product list and want to display all elements of the class in a ListView Widget?

class Product {
  final int id;
  final String name;
  final String image;
  final double price;
  int quantity;
}

I couldn't find a single Flutter example of this (probably because it is difficult to define the appropriate search keywords)!

Thanks pcsasa

CodePudding user response:

you can access the element from the Object Product and display in your custom widget.

eg:

List<Product> list = [...all your product];

...
// to display in Listview
 ListView.builder(
    shrinkWrap: true,
    itemCount: list.length,
    itemBuilder: (BuildContext context, int index) {
      return Column(
            children: [
               Text('${list[index].id}'), 
               Text('${list[index].name}'),
               Text('${list[index].quantity}'),
               Text('${list[index].price}'),
           ]
       );
    )

actually you can create your own widget to display all information from product. in this example, i just use a Column and a Text to display all the infromation from product .

  • Related