Home > database >  how to initState and get data from where firebase
how to initState and get data from where firebase

Time:01-09

i try to create many account and create blog and every account see blog that post by itself. how to init state where in firebase. I declare variable uid in class and get it from initstate and how to use where in firebase i try to mix it with streambuilder

i declare uid in class and get data by this

void inputData() {
    final User? user = auth.currentUser;
    setState(() {
      uid = user!.uid;
      // print('uid =======> $uid');
    });
  }

my initstate

@override
  initState() {
    super.initState();
    inputData();  }
final Stream<QuerySnapshot> animals = FirebaseFirestore.instance
      .collection('animal')
      .orderBy('createdate')
      // .where('uid', isEqualTo: uid)
      .snapshots();

after i use where here .I got error

The instance member 'uid' can't be accessed in an initializer. Try replacing the reference to the instance member with a different expression

StreamBuilder<QuerySnapshot>(
            stream: animals,
            builder: (
              BuildContext context,
              AsyncSnapshot<QuerySnapshot> snapshot,
            ) {
              if (snapshot.hasError) {
                return Text('Something Went Wrong!');
              }
              if (snapshot.connectionState == ConnectionState.waiting) {
                return Text('Loading');
              }

              final data = snapshot.requireData;

              return Container(
                margin: EdgeInsets.only(top: 65),
                child: ListView.builder(
                  shrinkWrap: true,
                  itemCount: data.size,
                  itemBuilder: (context, index) {
                    });
                    return ListTile(
                      title: Text(
                        '${data.docs[index]['animalName']}',
                      ),
                      subtitle: Text(
                        '${data.docs[index]['animalDetail']}',
                      ),
                      onLongPress: () async {
                        await processDeleteContent(context, data, index);
                      },
                    );
                  },
                ),
              );
            },
          ),

anyway to use where in streambuilder

CodePudding user response:

Your uid is set in initState() that calls after the class is initialized. So you get uid before it is set. Try to write your animals with get so it runs code written there only when you get animals but not on initialization:

Stream<QuerySnapshot> get animals => FirebaseFirestore.instance
      .collection('animal')
      .orderBy('createdate')
      .where('uid', isEqualTo: uid)
      .snapshots();
  •  Tags:  
  • Related