Reputation: 359
I have created a class like this
class Collection with ChangeNotifier {
List<Items> _items = [];
void addData(Items day) {
print(day.name);
print(day.id);
_items.add(day);
print(_items);
notifyListeners();
}
}
class Items {
String name;
String comments;
int id;
Items({required this.name, required this.comments, required this.id});
}
I am inserting data in _items like this
Collection().addData(Items(name: "a", comments: "sda", id: 12));
I can see on addData function its printing values correctly
but when i am showing this in my widget its not showing
ListView.builder(
itemCount: Collection()._items.length,
itemBuilder: (BuildContext context, int index) {
print(Collection()._items.length);
return Text('name ${Collection()._items[index].name} id ${Collection()._items[index].id}');
})
Upvotes: 0
Views: 802
Reputation: 12651
Each time you call the Collection()
constructor, you're making a different instance of the Collection
class. You need to create an instance using
final collection = Collection();
And then use that object in your builder.
It is better to use final
than var
, because that ensures that the collection
object won't get reassigned to a new instance.
Upvotes: 2