Getting Bool State from Firestore in Dart

764 views
Skip to first unread message

Alvaro Gonzalez Rico

unread,
Mar 17, 2021, 9:09:54 AM3/17/21
to Flutter Development (flutter-dev)
Hello! I am trying to get a bool value from Firestore when the app is being initialized: it returns True if it is "like" and False if it is not "like". Every time a user likes/unlikes a post, a database (called userFavorites) is being created or update on Firestore. The userFavorite database is composed of: document (user's ID), collection ('posts'), document (post's ID), collection (isLiked: true OR isLiked: false). So when initializing the app, I'm trying to get access to this True/False for each of the posts that are being displayed on the UI (if the user has never liked or unliked the post, the value for this bool will automatically be False). 

I would really appreciate if you can give me feedback/corrections on the code I use to get the True/False bool value from Firestore, because even though I am not getting any errors, the bool value on my IU is Null, and I don't know whether I made an error in this part of my code or in another part.

Here is the code I used:

class HomeFeed extends StatelessWidget {
  final user = FirebaseAuth.instance.currentUser;
  ValueKey valueKey; 

  Future<DocumentSnapshot> getDocumentSnapshotForCurrentUserLikes(String userId, String documentId) async {
    final String userId = user.uid;
    final String documentId = valueKey.value;
    return await FirebaseFirestore.instance.collection('userFavorites').doc(userId).collection('posts').doc(documentId).get();
  }
  bool getCurrentUserLikesValue(DocumentSnapshot documentSnapshotForCurrentUserLikes) {
    return documentSnapshotForCurrentUserLikes.data()['isLiked'];
  }

  @override
  Widget build(BuildContext context) {
    return StreamBuilder(
      stream: FirebaseFirestore.instance.collection('post').doc('Post in Feed').collection('posts').orderBy('createdAt', descending: true,).snapshots(),
      builder: (ctx, AsyncSnapshot<QuerySnapshot> postSnapshot) {
        if (postSnapshot.connectionState == ConnectionState.waiting) {
          return Center(
            child: CircularProgressIndicator(),
          );
        }
        final postDocs = postSnapshot.data.docs;
        return ListView.builder(
          reverse: false, 
          itemCount: postDocs.length,
          itemBuilder: (ctx, index) {
            ValueKey valueKey = ValueKey(postDocs[index].id);
            return Padding(
              padding: const EdgeInsets.all(8.0),
              child: Container(
                child: PostContainer(
                  user.uid,
                  postDocs[index].data()['likes'],
                  getCurrentUserLikesValue(postDocs[index]) == null ? false : getCurrentUserLikesValue(postDocs[index]), 
                  key: valueKey,
                ),
              ),
            );
          },
        );
      },
    );
  }
}

Suzuki Tomohiro

unread,
Mar 17, 2021, 9:22:25 AM3/17/21
to Flutter Development (flutter-dev)
Learn how to use the debugger and breakpoints. It gives correct answer why a variable is null. It more accurate than my eyes.

--
You received this message because you are subscribed to the Google Groups "Flutter Development (flutter-dev)" group.
To unsubscribe from this group and stop receiving emails from it, send an email to flutter-dev...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/flutter-dev/a3ee06f0-c066-4db3-aa9f-8e0744c93fcan%40googlegroups.com.

Alvaro Gonzalez Rico

unread,
Mar 29, 2021, 8:29:48 AM3/29/21
to Flutter Development (flutter-dev)
Hello! I have been researching and working on it for a while (also used the debugger and breakpoints every time), and the problem that I am having is that I am not able to get and display the T/F bool value from the Firestore database into the UI each time a post is initialized (or seen on the screen). What code could I use to do that? I would really appreciate your help here. Thanks!

Suzuki Tomohiro

unread,
Mar 29, 2021, 8:37:30 AM3/29/21
to Alvaro Gonzalez Rico, Flutter Development (flutter-dev)
I am not able to get and display the T/F bool value from the Firestore database into the UI each time a post is initialized (or seen on the screen)

Can you explain why you cannot do that?

Alvaro Gonzalez Rico

unread,
Mar 29, 2021, 8:57:57 AM3/29/21
to Flutter Development (flutter-dev)
Hello! Because I cannot figure out the code to get the specific bool value from the userFavorites database (the database that contains if a user has liked/unliked a post), and then have that bool value as the initial T/F (liked/not liked) each time a post is initialized. The identification of each post is the default ID that Firebase creates (the one you get by doing key.value), so when the data from the post database (the database with general info that each post has) is initialized at the beginning using a StreamBuilder, I am not able at that same time to get the data from userFavorites because I do not have the specific key.value for each post. As a result, I am not able to get the default T/F value from the userFavorites database each time a post is initialized. 

Suzuki Tomohiro

unread,
Mar 29, 2021, 9:21:17 AM3/29/21
to Alvaro Gonzalez Rico, Flutter Development (flutter-dev)
When a post is initialized, nobody has liked yet. So it’s false.

Alvaro Gonzalez Rico

unread,
Mar 29, 2021, 9:29:09 AM3/29/21
to Flutter Development (flutter-dev)
True, sorry I did not say it correctly. What I meant is that when a post in rendered on the UI. For example, if a user likes a post, and then closes the app, and 1hr later returns (at that point the app will be restarted), that post will be liked (because the post will get the info from the userFavorites database when it is rendered on the screen, and the data will say TRUE, because the user liked it 1hr before).

Alvaro Gonzalez Rico

unread,
Mar 30, 2021, 8:34:36 AM3/30/21
to Flutter Development (flutter-dev)
Hello! Were you able to find a possible solution for the issue I am having? Thanks

Suzuki Tomohiro

unread,
Mar 30, 2021, 8:57:48 AM3/30/21
to Alvaro Gonzalez Rico, Flutter Development (flutter-dev)
No, I don’t get the problem you’re facing. 

> because the post will get the info from the userFavorites database when it is rendered on the screen, and the data will say TRUE, because the user liked it 1hr before

Your problem is solved with the logic above, isn’t it?

Alvaro Gonzalez Rico

unread,
Mar 30, 2021, 9:12:03 AM3/30/21
to Flutter Development (flutter-dev)
Hello! Thanks for answering. This --> "because the post will get the info from the userFavorites database when it is rendered on the screen, and the data will say TRUE, because the user liked it 1hr before" <-- is what I want to do, BUT I do not know the code that I could use to do that. That's why I am having an issue.

Suzuki Tomohiro

unread,
Mar 30, 2021, 9:24:50 AM3/30/21
to Alvaro Gonzalez Rico, Flutter Development (flutter-dev)
It seems to me that you want to know how to read documents from Firestore. Can you share the URL of the documentation or tutorial you tried? Can you explain the difficulty?

Alvaro Gonzalez Rico

unread,
Mar 30, 2021, 10:15:38 AM3/30/21
to Flutter Development (flutter-dev)
Hello! I do know how to read documents from Firebase, what I do not know is how to read bool values and assign them to the T/F value of each post that is seen on the UI. Here is the video I tried to follow: https://www.youtube.com/watch?v=oF0Ro0SzbEs. On one page of my code I got the data (username, message, etc.) for each post from Firebase and rendered it on the UI using a StreamBuilder (this worked perfectly). Now, for each post, I want to give it a T/F value depending if the current user has liked the post in the past or not (this T/F value comes from another Firebase database called userFavorites). The identification of each post is the default ID that Firebase creates (the one you get by doing key.value), so when the data from the post database (the database with general info that each post has) is restarted at the beginning using a StreamBuilder, I am not able at that same time to get the data from userFavorites because I do not have the specific key.value for each post. As a result, I am not able to get the default T/F value from the userFavorites database each time a post is initialized. 

Suzuki Tomohiro

unread,
Mar 31, 2021, 11:49:00 PM3/31/21
to Alvaro Gonzalez Rico, Flutter Development (flutter-dev)
Can you share example data in userFavorites?

Alvaro Gonzalez Rico

unread,
Apr 2, 2021, 11:41:28 AM4/2/21
to Flutter Development (flutter-dev)
Hello!  I just finished working on this part and it works perfectly and smoothly. Thanks again for the quick response.

Suzuki Tomohiro

unread,
Apr 2, 2021, 12:49:51 PM4/2/21
to Alvaro Gonzalez Rico, Flutter Development (flutter-dev)
Can you share what was the problem and solution?

Alvaro Gonzalez Rico

unread,
Apr 4, 2021, 11:22:55 PM4/4/21
to Flutter Development (flutter-dev)
Hello! It was regarding getting the likes value from Firestore. Instead of saving in a database the likes value for each user for each post as T/F, I just saved in the post itself a collection of all the user IDs that liked that specific post. So I just used the get() to see if a specific user ID existed for each post. If it existed, the value was T, and if it did not exist, it was F. Then I used a FutureBuillder and passed this T/F for each post in the UI.

Suzuki Tomohiro

unread,
Apr 4, 2021, 11:31:29 PM4/4/21
to Flutter Development (flutter-dev)
Nice. Glad to hear it worked out.

Reply all
Reply to author
Forward
0 new messages