I have a bookmark list and I want to display only the Last/recent bookmark Book in the UI but couldn’t figure out a way to do it so any help or suggestion would be really appreciated.
I tried bookmarkedBook.last; but still didn’t work.
List<BookModel> bookmarkedBook = [];
late int bookId = 1;
@override
void initState() {
super.initState();
_updateTotalBookmarks();
}
void _updateTotalBookmarks() {
final bookmarkController =
provider.Provider.of<BookmarkController>(context, listen: false);
setState(() {
bookmarkedBook = bookmarkController.bookinStorage
.where((book) => bookmarkController.isBookBookmarked(book.id ?? -1))
.toList();
bookmarkedBook.last;
});
}
SingleChildScrollView(
child: provider.Consumer<BookmarkController>(
builder: (context, data, child) {
return Column(
children: [
ListView.builder(
physics: NeverScrollableScrollPhysics(),
shrinkWrap: true,
itemCount: bookmarkedBook.length,
itemBuilder: (BuildContext context, int index) {
final book = bookmarkedBook[index];
return GestureDetector(
onTap: () {
},
child: Container(
height: 200,
width: 130, // Specify the desired width
padding: EdgeInsets.fromLTRB(10, 0, 0, 0),
child: Column(
crossAxisAlignment:
CrossAxisAlignment.center,
children: [
Image.asset(
book.bookCoverPic ?? '',
height: 150,
width: 190,
),
],
),
),
);
},
),
],
);
},
),
),
3
Answers
According to my understanding you want to just slow the last bookmark into your UI.
In your ListView.builder you have given the itemCount as bookmarkedBook.length, so what it will do? it will populate all the bookmarks into your ListView. Now what you need to do?
Solution:
1- set ListView’s length as 1 (it will create only one item for listView)
2- refactor your itemBuilder, set book in itemBuilder like this
P.S. remove bookmarkedBook.last from your _updateTotalBookmarks() method
Do you want to display just the last bookmark (one bookmark)? or do you want to display bookmarks from recent to oldest?(Question from comments)
Case one: show only the last bookmark(only one )
Case 2: display bookmarks from recent to oldest
Reverse your list first
you can achieve this by adding a timestamp in the BookModel, then sort by that in reverse order before you take the first.
so your model will look like:
then when adding a bookmark you’ll have to set the timestamp, something like:
and then use the timestamp to sort the bookmark list in descending order:
so the first element will be the most recent like:
now you can display the most recent
you can refer to this documentation on how you can sort lists according to the order specified by the compare function.