How to check loggedinuser email in firestore database? Flutter

Viewed 32

Here is my code;

class TaskList extends StatefulWidget {
  @override
  _TaskListState createState() => _TaskListState();
}

class _TaskListState extends State<TaskList> {
  final _auth = FirebaseAuth.instance;

  void getCurrentUser() async {
    try {
      final user = await _auth.currentUser;
      if (user != null) {
        loggedInUser = user;
      }
    } catch (e) {
      print(e);
    }
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getCurrentUser();
  }

  @override
  Widget build(BuildContext context) {
    return StreamBuilder(
        stream: _firestore.collection('tasks').snapshots(),
        builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
          if (!snapshot.hasData) {
            return Padding(
              padding: EdgeInsets.only(top: 50, bottom: 50),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    "There is nothing to show for now!",
                    style: GoogleFonts.poppins(fontSize: 20),
                  ),
                  InkWell(
                    onTap: () {
                      Navigator.push(
                        context,
                        MaterialPageRoute(builder: (context) => AddTask()),
                      );
                    },
                    child: Container(
                      height: 80,
                      width: 80,
                      decoration: BoxDecoration(
                        color: Colors.blueAccent,
                        gradient: LinearGradient(
                          begin: Alignment.topRight,
                          end: Alignment.bottomRight,
                          colors: [Colors.blue, Colors.blueAccent],
                        ),
                        shape: BoxShape.circle,
                      ),
                      child: Center(
                        child: Icon(
                          Icons.add,
                          size: 35,
                          color: Colors.white,
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            );
          } else {
            return Padding(
              padding:
                  EdgeInsets.only(top: 50, bottom: 50, left: 20, right: 20),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Expanded(
                    child: ListView(
                      children:
                          snapshot.data!.docs.map((DocumentSnapshot document) {
                        Map<String, dynamic> data =
                            document.data()! as Map<String, dynamic>;
                        return Card(
                          child: Padding(
                            padding: EdgeInsets.only(
                                top: 10, bottom: 10, left: 10, right: 10),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Expanded(
                                  child: Column(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                    children: [
                                      Text(data['title'],
                                          style: kNormalTextStyle),
                                      Text(
                                        data['text'],
                                        style: kNormalTextStyle,
                                      ),
                                      Text(
                                        data['date'],
                                        style: kNormalTextStyle,
                                      ),
                                      Text(
                                        data['time'],
                                        style: kNormalTextStyle,
                                      ),
                                    ],
                                  ),
                                ),
                                IconButton(
                                  icon: Icon(Icons.delete),
                                  onPressed: () {},
                                )
                              ],
                            ),
                          ),
                        );
                      }).toList(),
                    ),
                  ),
                  InkWell(
                    onTap: () {
                      Navigator.push(
                        context,
                        MaterialPageRoute(builder: (context) => AddTask()),
                      );
                    },
                    child: Container(
                      height: 80,
                      width: 80,
                      decoration: BoxDecoration(
                        color: Colors.blueAccent,
                        gradient: LinearGradient(
                          begin: Alignment.topRight,
                          end: Alignment.bottomRight,
                          colors: [Colors.blue, Colors.blueAccent],
                        ),
                        shape: BoxShape.circle,
                      ),
                      child: Center(
                        child: Icon(
                          Icons.add,
                          size: 35,
                          color: Colors.white,
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            );
          }
        });
  }
}

What I'm tryin to do is if there is a task with email as same as loggedInUser, I want to show it AllTasks page.

return StreamBuilder(
    stream: _firestore.collection('tasks').snapshots(),
    builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
      if (!snapshot.hasData) 

In this code part, I can check if there is any data in snapshot however, I want to check if there is a task with mail as same as loggedInUser.email. Is there a way to check if there is a task with email as same as loggedInUser?

loggedInUser implementation:

User? loggedInUser;

Also how I add data to firestore database:

ElevatedButton(
              child: Text("Add Task"),
              onPressed: () {
                String formatedDate =
                    DateFormat("MM-dd-yyyy").format(_selectedDate!);
                String formattedTime =
                    DateFormat("HH:mm").format(_dateTime!);
                _firestore.collection("tasks").add({
                  'title': _titleController.text,
                  'text': _textController.text,
                  'date': formatedDate,
                  'time': formattedTime,
                  'email': loggedInUser!.email,
                });

                Navigator.pop(context, _firestore);
              },
            ),
1 Answers

If you only want to show the tasks for the logged in user, it is best to use a query to only read those tasks from the database.

stream: _firestore.collection('tasks').where('email', isEqualTo: loggedInUser!.email).snapshots(),

Also see the FlutterFire documentation on filtering data through queries.

Related