How put a future inside initState?
376
You could just do this:
Future getNewUid() async {
CollectionReference Users = FirebaseFirestore.instance.collection('Users');
var response = await Users
.doc(snapshot.data.docs[index]['uid']) //it doesn't take informations and it's red underlined
.get();
newUid = response.data;
}
@override
void initState() {
getNewUid();
super.initState();
}
Comments
-
flowey over 1 year
I created a list but I put it my future in a stream builder and it rebuilds when I scroll so I'm trying to create a future method outside in initstate that I'll call in my code.
The problem is I used in the docs(), informations from streamBuilder so I can't access to these, when my code is outside. How can I do ?
This is my code
Future getNewUid() async { CollectionReference Users = FirebaseFirestore.instance.collection('Users'); var response = await Users .doc(snapshot.data.docs[index]['uid']) //it doesn't take informations and it's red underlined .get(); return response.data; } @override void initState() { var newUid = getNewUid(); print(newUid); super.initState(); }
And the rest
body: StreamBuilder( stream: BusiPosts.orderBy('time', descending: true).snapshots(), builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) { if (snapshot.hasError) { return Text('Something went wrong'); } if (snapshot.connectionState == ConnectionState.waiting) { return Center( child: CircularProgressIndicator()); } return ListView.builder( itemCount: snapshot.data.docs.length, itemBuilder: (context, index) { return Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ ListTile( title: FutureBuilder<DocumentSnapshot>( future: newUid, builder: (BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot) { if (snapshot.hasError) { return Text("Something went wrong"); } if (snapshot.hasData && !snapshot.data!.exists) { return Text("Document does not exist"); } if (snapshot.connectionState == ConnectionState.done) { Map<String, dynamic> data = snapshot.data!.data() as Map<String, dynamic>; return GestureDetector( onTap: () => navigateToDetail(data[index]),
I tried to edit with no success :/
CollectionReference Users = FirebaseFirestore.instance.collection('Users'); var futureResult = await Users .doc(snapshot.data.docs[index]['uid']) //it doesn't take informations and it's red underlined .get(); return futureResult; } void initState() async{ var futureResult = await myFutureFunction(); super.initState(); }
-
flowey over 2 yearsThe problem is it doesn't take the informations from ` .doc(snapshot.data.docs[index]['uid'])` because it comes from my stream builder insided my code to have the uid of the person who posted