Jan Feder
Jan Feder

Reputation: 25

Flutter: Firebase read data from userID

I'm building a ToDo App with Flutter. Now I've added an anonymous login so every device has its own ToDos. But all devices still show the same ToDos. I tried to add .document(user.uid) but that didn't work because "user" got underlined red. So how can I read the data of just the one user on this device? Another problem I run into is that the ToDo doesn't add to the existing inside the userID document in the database, else it just updates the "old" one. This is my code: (Let me know if you need another part of the code)

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {


  String input = "";


  createTodos() async{
    FirebaseUser user = await FirebaseAuth.instance.currentUser();
    DocumentReference documentReference =
    Firestore.instance.collection("MyTodos").document(user.uid);

    //Map
    Map<String, String> todos = {"todoTitle": input};

    documentReference.setData(todos).whenComplete(() {
      print("$input created");
    });
  }

  deleteTodos(item) {
    DocumentReference documentReference =
    Firestore.instance.collection("users").document();


    documentReference.delete().whenComplete(() {
      print("$item deleted");
    });
  }

  moveTodos(item) {
    DocumentReference documentReference =
    Firestore.instance.collection("users").document(item);

    //Map
    Map<String, String> todos = {"todoMove": item};

    documentReference.setData(todos).whenComplete(() {
      print("$input moved");
    });
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton: FloatingActionButton(
          onPressed: () {
            showDialog(
                context: context,
                builder: (BuildContext context) {
                  return AlertDialog(
                    backgroundColor: Colors.grey[300],
                    title: Text('Add ToDo',
                      style: TextStyle(fontWeight: FontWeight.bold),),
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(15)
                    ),
                    content: TextField(
                      onChanged: (String value) {
                        input = value;
                      },
                    ),
                    actions: <Widget>[
                      FlatButton(
                          onPressed: () {
                            createTodos();

                            Navigator.of(context).pop();
                          },
                          child: Text('Add'))
                    ],
                  );
                });
          },
          child: Container(
            width: 200,
            height: 200,
            child: Icon(Icons.add, color: Colors.grey[700],),
            decoration: BoxDecoration(
                color: Colors.grey[300],
                borderRadius: BorderRadius.all(Radius.circular(50)),
                boxShadow: [
                  BoxShadow(
                      color: Colors.grey[500],
                      offset: Offset(4.0, 4.0),
                      blurRadius: 15.0,
                      spreadRadius: 1.0
                  ),
                  BoxShadow(
                      color: Colors.white,
                      offset: Offset(-4.0, -4.0),
                      blurRadius: 15.0,
                      spreadRadius: 1.0
                  ),
                ]
            ),
          )
      ),
      body: StreamBuilder(
          stream: Firestore.instance.collection("users").snapshots(),
          builder: (context, snapshots){

            if(snapshots.data == null) return CircularProgressIndicator();

            return ListView.builder(
                shrinkWrap: true,
                itemCount: snapshots.data.documents.length,
                itemBuilder: (context, index) {
                  DocumentSnapshot documentSnapshot = snapshots.data.documents[index];
                  return Dismissible(
                    background: Container(
                      color: Colors.green,
                      alignment: Alignment(-0.9, 0),
                      child: Icon(Icons.check, color: Colors.white,),
                    ),
                    secondaryBackground: Container(
                      color: Colors.red,
                      alignment: Alignment(0.9, 0),
                      child: Icon(Icons.delete, color: Colors.white,),
                    ),
                    onDismissed: (direction) {
                      if (direction == DismissDirection.startToEnd) {
                        moveTodos(documentSnapshot["todoTitle"]);
                        deleteTodos(documentSnapshot["todoTitle"]);
                      } else
                      if (direction == DismissDirection.endToStart) {
                        deleteTodos(documentSnapshot["todoTitle"]);
                      }
                    },
                    key: Key(documentSnapshot["todoTitle"]),
                    child: Container(
                      margin: EdgeInsets.all(8),
                      child: Card(
                        margin: EdgeInsets.zero,
                        shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(10)
                        ),
                        color: Colors.grey[300],
                        child: ListTile(
                          title: Text(documentSnapshot["todoTitle"] ?? "No ToDos yet!"),
                          trailing: Wrap(
                            children: <Widget>[
                              IconButton(
                                  icon: Icon(Icons.check),
                                  color: Colors.green,
                                  onPressed: (){
                                    moveTodos(documentSnapshot["todoTitle"]);
                                    deleteTodos(documentSnapshot["todoTitle"]);
                                  } ),
                              IconButton(
                                  icon: Icon(Icons.delete),
                                  color: Colors.red,
                                  onPressed: (){
                                    deleteTodos(documentSnapshot["todoTitle"]);
                                  } ),
                            ],
                          )
                        ),
                      ),
                      decoration: BoxDecoration(
                          color: Colors.grey[300],
                          borderRadius: BorderRadius.all(Radius.circular(10)),
                          boxShadow: [
                            BoxShadow(
                                color: Colors.grey[500],
                                offset: Offset(4.0, 4.0),
                                blurRadius: 15.0,
                                spreadRadius: 1.0
                            ),
                            BoxShadow(
                                color: Colors.white,
                                offset: Offset(-4.0, -4.0),
                                blurRadius: 15.0,
                                spreadRadius: 1.0
                            ),
                          ]
                      ),
                    ),
                  );
                });
          }),
      backgroundColor: Colors.grey[300],
    );
  }
}

Upvotes: 0

Views: 770

Answers (1)

Sukhi
Sukhi

Reputation: 14215

The problem is in the line below :

stream: Firestore.instance.collection("users").snapshots(),

It basically grabs everything in the 'users' collection and displayes it to everyone. You just have to add a user specific filter while grabbing the data from the Firestore. You might want to add the filter as :

stream: Firestore.instance.collection("users")
  .where('userId', isEqualTo: user.uid)
  .snapshots()

Upvotes: 2

Related Questions