Jovane Mullings
Jovane Mullings

Reputation: 87

Is there a way to compare two list and check for the value that are the same

I am create a social media type app I want to create a follower and following list like Instagram, I want when I go on some else profile and click on their followers or following list it shows a list of all the users that is following that person and if I am also following someone in the list it give me the option to unfollow that person and if I am not following the same person it gives me the option to follow them.

The code below is what I was to check if I am following any one in profile user followers list, What I have done is I query the data from firestore of all the user id the I am following and the same for user profile that is currently open and store the list in two separate variable and what it should do is check both list and if a user Id is in both list it means I am also following that user and should show that I am following that user and give the option to unfollow but what happens is instead of showing that I am only following the user who's id is in both list it show that I am following every one.

checkfollowers(BuildContext context, String? id) async {
    final auth = Provider.of<AuthState>(context, listen: false);
    List<String> followingList = [];
    List<String> myFollowingList = [];

    try {
      final QuerySnapshot following = await _firestore
          .collection('following')
          .doc(auth.getCurrentUser.uid)
          .collection('userFollowing')
          .get();

      QuerySnapshot userfollowing = await _firestore
          .collection('followers')
          .doc(id)
          .collection('userFollowers')
          .get();

      following.docs.forEach((element) {
        myFollowingList.add(element.id);
      });
      userfollowing.docs.forEach((element) {
        followingList.add(element.id);
      });

      // followingList.where((item) => myFollowingList.contains(item));

      check(value) => myFollowingList.contains(value);
      isFollowedByMe = followingList.any(check);
      notifyListeners();

      print(followingList);
      print(myFollowingList);
    } catch (err) {
      print(err.toString() + 'this error is coming from profileState');
    }
  }

below code is how I build the follower/following list

 final FirebaseFirestore _firestore = FirebaseFirestore.instance;
  UserModel? users;

  @override
  void initState() {
    final profileState = Provider.of<ProfileState>(context, listen: false);
    profileState.checkfollowers(context, widget.proFileId);
    super.initState();
  }

  userComponent(UserModel? model, BuildContext context) {
    final profileState = Provider.of<ProfileState>(context);
    final auth = Provider.of<AuthState>(context);

    return Container(
      margin: EdgeInsets.symmetric(horizontal: 10),
      padding: EdgeInsets.only(top: 10, bottom: 10),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          GestureDetector(
            onTap: () {
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) =>
                      ProfilePage(profileId: '${model?.userId}'),
                ),
              );
            },
            child: Row(
              children: [
                Container(
                  width: 60,
                  height: 60,
                  child: CircleAvatar(
                    radius: 50,
                    backgroundImage: NetworkImage('${model?.profilePic}'),
                  ),
                ),
                SizedBox(width: 10),
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Text('${model?.userName}',
                        style: TextStyle(
                            color: Colors.black, fontWeight: FontWeight.w500)),
                    SizedBox(
                      height: 5,
                    ),
                    Text(
                      '${model?.displayName}',
                      style: TextStyle(
                        color: Colors.grey[500],
                      ),
                    ),
                  ],
                )
              ],
            ),
          ),
          auth.getCurrentUser.uid == model?.userId
              ? Container()
              : GestureDetector(
                  onTap: () {
                    if (auth.getCurrentUser.uid == model?.userId) {
                      print('you can not follow your self');
                    } else if (profileState.isFollowedByMe == true) {
                      profileState.setIsFollowedByMeToFalse();
                      profileState.handleUnFollow(context, model?.userId);
                    } else if (profileState.isFollowedByMe == false) {
                      profileState.setIsFollowedByMeToTrue();
                      profileState.handleFollow(context, model?.userId);
                    }
                  },
                  child: AnimatedContainer(
                    height: 35,
                    width: 110,
                    duration: Duration(milliseconds: 300),
                    decoration: BoxDecoration(
                      color: profileState.isFollowedByMe == true
                          ? AppColors.white
                          : AppColors.pinkaccent,
                      borderRadius: BorderRadius.circular(5),
                      border: Border.all(
                        color: Colors.grey.shade700,
                      ),
                    ),
                    child: Center(
                      child: Text(
                        profileState.isFollowedByMe == true
                            ? 'UnFollow'
                            : 'Follow',
                        style: TextStyle(
                            color: profileState.isFollowedByMe == true
                                ? Colors.black
                                : Colors.white),
                      ),
                    ),
                  ),
                )
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        elevation: 0,
        backgroundColor: Colors.white,
        title: Container(
          height: 38,
          child: TextField(
            onChanged: (value) {},
            decoration: InputDecoration(
                filled: true,
                fillColor: Colors.white,
                contentPadding: EdgeInsets.all(0),
                prefixIcon: Icon(
                  Icons.search,
                  color: Colors.grey.shade500,
                ),
                border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(50),
                    borderSide: BorderSide.none),
                hintStyle: TextStyle(fontSize: 14, color: Colors.grey.shade500),
                hintText: "Search users"),
          ),
        ),
      ),
      body: StreamListWrapper(
        stream: _firestore
            .collection('followers')
            .doc(widget.proFileId)
            .collection('userFollowers')
            .snapshots(),
        itemBuilder: (context, DocumentSnapshot snapshot) {
          var data = snapshot.data() as Map<String, dynamic>;
          users = UserModel.fromJson(data);
          return userComponent(users, context);
        },
        text: '${widget.user?.userName} as no Followers',
      ),
    );

Upvotes: 0

Views: 197

Answers (1)

mmcdon20
mmcdon20

Reputation: 6696

It would be simpler (and more performant) to use the Set data structure rather than List. The intersection method on Set returns the items contained in both sets.

for example:

void main() {
  Set<String> followingSet = {'Jeff', 'Mike', 'Joe', 'Jess'};
  Set<String> myFollowingSet = {'Jess', 'Matt', 'Mike', 'Frank'};
  Set<String> usersInBothSets = followingSet.intersection(myFollowingSet);
  print(usersInBothSets); // {Mike, Jess}
}

Upvotes: 2

Related Questions