Jeevan Shrestha
Jeevan Shrestha

Reputation: 273

How to access model data of type List having multiple item in each class in ListView.builder

I am making a simple app which has a model with 2 items in it. I want to access the list in listView builder but it gives an error:

The operator '[]' isn't defined for the class 'FirstSem'. lib/main.dart:72 - 'FirstSem' is from 'package:project/model/model.dart' ('lib/model/model.dart'). package:project/model/model.dart:1 Try correcting the operator to an existing operator, or defining a '[]' operator. trailing: Text(student[index].code)

Suggest me a good way to access it. Thanks in advance. Here is my code:

model.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),
  );
})

Upvotes: 2

Views: 1226

Answers (2)

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 🎉🎉🎉

Upvotes: 3

AnhPC03
AnhPC03

Reputation: 646

FirstSem is class, not object. Change the FirstSem to subject list like this

ListView.builder(
              itemCount:subject.length,
              itemBuilder: (context,index){
                    final _subject = subject[index];
                    return ListTile(
                      title: Text(_subject.title),
                      trailing: Text(_subject.code),
                    );
                  })

Upvotes: 2

Related Questions