I’m not sure if my strategy or logic is correct to achieve this, but I have 2 lists coming from 2 different jsondata mysql queries, let’s say they look like this:
List newsAgency = [{id: 1, name: 9news, image: x}
{id: 2, name: abcnews, image: y}
{id: 3, name: bbcnews, image:z}];
List following = [{userid: 41, username: x, newsid: 2}
{userid: 41, username: x newsid: 3}];
I want to see if the id in newsAgency
matches the newsid
in the following list, and to return true or false correspondingly.
The idea is to say that I am following 2 news agencies out of 3, so my goal is to display the button to follow or unfollow based on the results.
I tried everything suggested from this post how can I find a list contains in any element another list in flutter? but couldn’t get it.
This is my code example:
Listview.builder(
itemCount: newsAgency.length,
itemBuilder: (BuildContext context, int index) {
bool following = false;
return Card(
elevation: 10.0,
child: Row(
children: [
Text(newsAgency[index]['name'],
following
? TextButton(onPressed: () {//unfollow function},
child: const Text('unfollow')),
: TextButton(onPressed: () {//follow function},
child: const Text('follow')),
]));});
Any help is highly appreciated
2
Answers
add this method in your class, it will be responsible for searching which items are following and which are not, and return a bool based on it:
now inside of your
ListView
‘sitemBuilder
, replace this:with this:
following
will be true or false based on if the current Agency’sid
exists in some item in the following list.use contains() method to check if the list contains the value you want to match or not, for example:-
following.contains(newsAgency[index]['name'].toString())
// true if value matches.