2

I am a girl new for StackOverFlow and Flutter. I am dev my first app in Flutter and I connected succesfully login and Signup form with AUTH firebase. Now I created another form in the app which collect other details from the user, it is an address book. this address book create a new collection into firestore and in another screen of flutter I want to get these data, but just for the user logged in, at moment I can retrieve the data using streambuilder but I get the data from all the documents in firestore. I think I need to use something called user_id into my fields to import only the data from the specific user logged. Any good dev here is ready to help me? below the user creating...

try {
                            final newUser =
                            await _auth.createUserWithEmailAndPassword(
                                email: email, password: password);
                            if (newUser != null) {
                              Navigation..);
                            }

this is to create a new collection in firestore

void createRecord() async {
    await databaseReference.collection("shippingAddress").add({
      'alias': '$alias',
      'shippingName': '$shippingName',
      'shippinglastName': '$shippinglastName',
      'street': '$street',
      'streetNumber': '$streetNumber',
      'zipNumber': '$zipNumber',
      'phoneNumber': '$phoneNumber',
      'textMessage': '$textMessage',
      'totalQuantity': '$totalQuantity',
      'totalWeight': '$totalWeight',
    }).then((value) {
      print(value.documentID);
    });
  }

now I need to get this above collection but just for the user logged and I used this code:

return StreamBuilder(
      stream: Firestore.instance.collection('shippingAddress').snapshots(),
      builder: (context, snapshot) {
        if (!snapshot.hasData) return Text('Loading data please Wait');
        return Column(
          children: <Widget>[
            Container(
              height: 350,
              child: ListView.builder(
                shrinkWrap: true,
                itemCount: snapshot.data.documents.length,
                itemBuilder: (BuildContext context, int index) {
                  return Card(
                    color: Color(0xFF1f2032),
                    elevation: 15,
                    child: Container(
                      width: 60,
                      height: 60,
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceAround,
                        children: <Widget>[
                          Card(
                            color: Color(0xfffeaf0d),
                            child: Container(
                                height: 40,
                                width: 40,
                                child: Icon(
                                  Icons.local_shipping,
                                  color: Colors.white,
                                  size: 25,
                                )),
                          ),
                          Text(
                            snapshot.data.documents[index]['alias'],

With the code above I get all the data into the widget but not for a specific user. here the get code

class CollectData extends StatefulWidget {
  @override
  _CollectDataState createState() => _CollectDataState();
}

class _CollectDataState extends State<CollectData> {

  String phone, wifeName, preferredLocation;

  _CollectDataState({this.phone,this.wifeName,this.preferredLocation});


  Stream<DocumentSnapshot> getData() async* {
    FirebaseUser user = await FirebaseAuth.instance.currentUser();
    yield* Firestore.instance.collection('shippingAddress').document(user.uid).snapshots();
  }
  @override
  Widget build(BuildContext context,) {
    return StreamBuilder(
      stream: getData(),
      builder: (context, snapshot){
        return Column(
          children: [
            Text(phone),
            Text(wifeName),
            Text(preferredLocation),
          ],
        );
      },
    );
  }
}

I got A non-null String must be provided to a Text widget.

Please help

1 Answer 1

2

When creating a new document, you can use the userId as a document id:

void createRecord() async {
FirebaseUser user = await FirebaseAuth.instance.currentUser();
 await databaseReference.collection("shippingAddress").document(user.uid).setData({
      'alias': '$alias',
      'shippingName': '$shippingName',
      'shippinglastName': '$shippinglastName',
      'street': '$street',
      'streetNumber': '$streetNumber',
      'zipNumber': '$zipNumber',
      'phoneNumber': '$phoneNumber',
      'textMessage': '$textMessage',
      'totalQuantity': '$totalQuantity',
      'totalWeight': '$totalWeight',
    }).then((value) {
      });
  }

Then when using the StreamBuilder you can retrieve data from the logged in user, create a method that returns a Stream:

   Stream<DocumentSnapshot> getData()async*{
     FirebaseUser user = await FirebaseAuth.instance.currentUser();
     yield* Firestore.instance.collection('shippingAddress').document(user.uid).snapshots();
  }

inside the `StreamBuilder:

return StreamBuilder(
      stream: getData(),
      builder: (context, snapshot) {
Sign up to request clarification or add additional context in comments.

6 Comments

can I ask you if you can write me a full code to see what is wrong with mine? please.
Into the VOID " createRecord" I got error on FirebaseAuth.instance.currentUser() :A value of type 'Future<FirebaseUser>' can't be assigned to a variable of type 'FirebaseUser'. Try changing the type of the variable, or casting the right-hand type to 'FirebaseUser'. and: print(value.documentID); I got This expression has a type of 'void' so its value can't be used.
Yes! now createRecord works pretty nice, I have edited question and added getData that return error please check, dont worry about documents collection I just changed. but I cant get them into widget
all of those String phone, wifeName, preferredLocation are null
I added; Text(snapshot.data['phone']), as widget and it works
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.