Reputation: 389
I'm trying to allow a user to mark a post being built by a ListView.builder as a like . With my current code, when a user like one post, all posts are marked as favorite. I would like the user to be able to add each post individually as a like and persist that favorite after a restart. I have the data saved to an api but it seems like this should be handled in the app itself.
Here is my code:
bool isFavourite = false;
ListView.builder(
itemCount: serviceProvider.justPostsModel.length,
itemBuilder: (context, index) {
return Padding(
padding: const EdgeInsets.only(left: 4.0, right: 4.0, bottom: 4),
child: InkWell(
onTap: () {
},
child: Container(
width: MediaQuery.of(context).size.width,
child: Card(
child: Column(
children: [
Padding(
padding:
const EdgeInsets.only(left: 8.0, right: 12),
child: Row(
children: [
InkWell(
onTap: () async {
if (isFavourite == false) {
await serviceProvider.setToggleLike(
context,
serviceProvider
.justPostsModel[index].id);
await serviceProvider
.getPostsList(context);
setState(() {
isFavourite = true;
});
} else {
await serviceProvider.setToggleLike(
context,
serviceProvider
.justPostsModel[index].id);
await serviceProvider
.getPostsList(context);
setState(() {
isFavourite = false;
});
}
},
child: Icon(
isFavourite == false
? Icons.favorite_border
: Icons.favorite,
color: Constants.skyColor(),
),
),
],
),
),
]),
),
),
),
);
},
),
So , how can i do that in best way !
Upvotes: 1
Views: 1849
Reputation: 629
You should have a list that contains favoriteStatus.
//length should be equal serviceProvider.justPostsModel.length
//put some initial value (true, false) in each index according to its favorite status
List<bool> isFavourite;
then
ListView.builder(
itemCount: serviceProvider.justPostsModel.length,
itemBuilder: (context, index) {
return Padding(
padding: const EdgeInsets.only(left: 4.0, right: 4.0, bottom: 4),
child: InkWell(
onTap: () {
},
child: Container(
width: MediaQuery.of(context).size.width,
child: Card(
child: Column(
children: [
Padding(
padding:
const EdgeInsets.only(left: 8.0, right: 12),
child: Row(
children: [
InkWell(
onTap: () async {
if (isFavourite[index] == false) {
await serviceProvider.setToggleLike(
context,
serviceProvider
.justPostsModel[index].id);
await serviceProvider
.getPostsList(context);
setState(() {
isFavourite[index] = true;
});
} else {
await serviceProvider.setToggleLike(
context,
serviceProvider
.justPostsModel[index].id);
await serviceProvider
.getPostsList(context);
setState(() {
isFavourite[index] = false;
});
}
},
child: Icon(
isFavourite[index] == false
? Icons.favorite_border
: Icons.favorite,
color: Constants.skyColor(),
),
),
],
),
),
]),
),
),
),
);
},
),
Upvotes: 1
Reputation: 388
Each post should have isLiked fields in database and based on this condition You can display whether it is liked or not.
Upvotes: 0