Home > Back-end >  how to access model data of type List having multiple item in each class in ListView.builder
how to access model data of type List having multiple item in each class in ListView.builder

Time:07-24

I am making a simple app which have a model with 2 item in it.I want to access the list in listview builder but it gives an error.Suggest me a good way to access it.Thank in advance. Here is my code:

moel.dart

import 'package:flutter/material.dart';

class FirstSem{
  String? title;
  String? code;
  FirstSem({this.title,this.code});
}
List <FirstSem> subject=[
FirstSem(title: "MatheMatics",code: "MTH162"),
FirstSem(title:"Physice",code:"Phy162"),
FirstSem(title:"Digital Logic",code:"csc 162"),
FirstSem(title:"C Programming",code:"csc 159"),
FirstSem(title:"Introduction of Information Technology",code:"csc 160"),
];

main.dart

ListView.builder(itemCount:5,itemBuilder: (context,index){
                    return ListTile(
                      title: Text(FirstSem[index].title),
                      trailing: Text(FirstSem[index].code),
                    );
                  })

CodePudding user response:

This is very simple to solve ✔️

You're trying to access item at index index of a dart Class. This is only possible on Lists

  • Changing your Text(FirstSem[index].title) to Text(subject[index].title) and

  • Setting your itemCount to subject.length will definitely solve your problem

Happy coding

  • Related