简体   繁体   中英

How to get String data from field inside a refrenced document (Firebase)

In my Flutter Application I would like to get some information from a field which contains a refrence to another Collection. I don't know how to get to the information from the field inside the referenced document.

Down below are two pictures of both collections.

The first picture contains the main collection where the field ("geslacht") refers to: "/gender/Girl"

收集1

The second picture shows the referenced collection.

收集2

I currently have written the following piece (following this tutorial )

class Record {
  final String name;
  var color;
  final DocumentReference reference;
  Record.fromMap(Map<String, dynamic> map, {this.reference})
      : assert(map['name'] != null),
        assert(map['geslacht'] != null),
        name = map['name'],
        color = map['geslacht'];
  Record.fromSnapshot(DocumentSnapshot snapshot)
      : this.fromMap(snapshot.data, reference: snapshot.reference);  
  @override
  String toString() => "Record<$name:$votes>";
}

Which perfectly gets the data from the field called "name" and returns a instance of DocumentReference for the field called "geslacht"

I would love to get the information in this referenced document. So to conclude the value "pink" is what I am trying a get. (The path would be baby --> dana --> geslacht --> gender --> girl --> color --> pink )

Thanks in advance for the help!

You will have to get() the other document using that DocumentReference, just like you would if you built the DocumentReference yourself. Cloud Firestore will not automatically follow references for you - you have to write code for that.

You need to query for your data using that reference, you currently only grab that first document:

class Record {
  final String name;
  var color;
  final DocumentReference reference;
  Record.fromMap(Map<String, dynamic> map, {this.reference})
      : assert(map['name'] != null),
        assert(map['geslacht'] != null),
        name = map['name'],
        color = map['geslacht'];
  Record.fromSnapshot(DocumentSnapshot snapshot)
      : this.fromMap(snapshot.data, reference: snapshot.reference);  
  @override
  String toString() => "Record<$name:$votes>";
}

What you need to do is to perform another query like this:

_getGender(ref) async {
  // ref is '/gender/Girl/' in your case
  var query = await Firestore.instance.document(ref).get();
  print('color is: ' + query.data['color'])
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM