0

I have a Flutter app where I'm trying to get a specific data from Firebase a save it into a variable. In Firebase, I'm using Firestore Database and the structure of my database is like that:

enter image description here

I'm trying to get the data using this method:

  void getItems() async {
    var test;
    FirebaseFirestore.instance
        .collection("userData")
        .doc(Constant.loginID)
        .get()
        .then((DocumentSnapshot doc) => print(doc.data()) );
  
  }

With this code I get the data of a specific document and that is okay, however I get all the data of that document and I only want "useItems" data, How I can do it?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807

1 Answers1

1

In my knowledge ,from cloud firestore collection you can query from subcollection, but not form tis Map

so if you get need only userItem then (you will get all data to the app and take needed data form app side)

 void getItems() async {
var test;
FirebaseFirestore.instance
    .collection("userData")
    .doc(Constant.loginID)
    .get()
    .then((DocumentSnapshot doc) => print(doc.data['userItem']) );

or Create a model Class and use userItem object;

you can also do it from ui side

class UserInformation extends StatefulWidget {
      @override
  _UserInformationState createState() => _UserInformationState();
   }

     class _UserInformationState extends State<UserInformation> {
    final Stream<QuerySnapshot> _usersStream = 
      FirebaseFirestore.instance.collection('users').snapshots();

    @override
     Widget build(BuildContext context) {
       return StreamBuilder<QuerySnapshot>(
     stream: _usersStream,
      builder: (BuildContext context, 
     AsyncSnapshot<QuerySnapshot> snapshot) {
    if (snapshot.hasError) {
      return Text('Something went wrong');
    }

    if (snapshot.connectionState == ConnectionState.waiting) {
      return Text("Loading");
    }

    return ListView(
      children: snapshot.data!.docs.map((DocumentSnapshot document) {
      Map<String, dynamic> data = document.data()! as Map<String, dynamic>;
        return ListTile(
          title: Text(data['userItem']),
       
        );
      }).toList(),
    );
  },
);
  }
 }
Akbar Masterpadi
  • 976
  • 8
  • 15
  • your code not work because "The operator '[]' isn't defined for the type 'Object Function()'. Try defining the operator '[]'" however, actually I get all data, so how I can take needed data? – Juan Sin Miedo Jul 30 '22 at 18:46
  • updated can you try both methods? for more visit https://firebase.flutter.dev/docs/firestore/usage/ – Akbar Masterpadi Jul 30 '22 at 18:58
  • The first one does not, however the second one does not give me any error. However, this is not my objective, I mean I don't want to show the data I want to get the data and save it in a variable as string – Juan Sin Miedo Jul 30 '22 at 21:40