arraysflutterdart-2

How to compare 2 arrays of different lengths and look for matching values - Flutter


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


Solution

  • 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:

      bool checkIsFollowing(Map<String, dynamic> current) {
        for(int index = 0; index < following.length; index+=1) {
          if(current["id"] == following[index]["newsid"]) {
            return true;
          }
        }
        return false;
      }
    

    now inside of your ListView's itemBuilder, replace this:

        bool following = false;
    

    with this:

     final currentNewsAgency = newsAgency[index];
     bool following = checkIsFollowing(currentNewsAgency);
     
    

    following will be true or false based on if the current Agency's id exists in some item in the following list.