Home > Mobile >  Fetching data from firestore and displaying it in my flutter code
Fetching data from firestore and displaying it in my flutter code

Time:07-13

I'am making a user profile in flutter. I wanted to display the data from my database that I made in Firebase. I get an error in my text saying that the operator [] isn't defined for the type QuerySnapshot. How can I resolve this. Thank you

class _ProfileState extends State<Profile> {
  final Stream<QuerySnapshot> users =
  FirebaseFirestore.instance.collection('users').snapshots();
@override
Widget build(BuildContext context) {
return Scaffold(
    body: SizedBox(
        child: Column(
            children: [
              Expanded(
                  child: Column(
                children: [
                  
                  StreamBuilder<QuerySnapshot>(
                    stream: users,
                    builder: (
                      BuildContext context,
                      AsyncSnapshot<QuerySnapshot> snapshot,
                    ) {
                        if (snapshot.hasError) {
                        var data = 'Something went wrong.!';
                        return Text(data);
                      }
                      if (snapshot.connectionState ==
                          ConnectionState.waiting) {
                        return const Text ('loading');
                      }
                                  Column(children: const [
                                    Text(
                                      '${data['name']}',
                                    ),
                                   Text(
                                      '${data['age']}',
                                    ),
                                  ])
                    },
  )
                ],
              )),
            ])));
}}

CodePudding user response:

Try this:

StreamBuilder<QuerySnapshot>(
              stream: FirebaseFirestore.instance
                  .collection(AppConfig.instance.cUser)
                  .snapshots(),
              builder: (BuildContext context,
                  AsyncSnapshot<QuerySnapshot> chatSnapshot) {
                if (chatSnapshot.connectionState == ConnectionState.waiting) {
                  return Center(
                    child: Container(),
                  );
                }
                return ListView(
                  reverse: true,
                  controller: _controller,
                  physics: const BouncingScrollPhysics(),
                  children:
                      chatSnapshot.data!.docs.map((DocumentSnapshot document) {
                    Map<String, dynamic> data =
                        document.data()! as Map<String, dynamic>;
                    return Text(data['text']);
                  }).toList(),
                );
              },
            ),

CodePudding user response:

Use hasData to check that snapshot contains a non-null value and data to access it.

  • Related