I am having a trouble accessing a single data from Firestore. Since accessing data from Firestore is a future whenever I try to call it from initState and setState it, it just prints null
so I decided to use a FutureBuilder. So now, is it possible to access the return data from a FutureBuilder to the another page from page1.dart
to page2.dart
?
page1.dart
class FetchSingleData extends StatelessWidget {
// I want to access this one
String? uniqueHandler;
FetchSingleData({super.key, this.uniqueHandler});
Future<QuerySnapshot> fetchUniqueHanlder() async {
return await FirebaseFirestore.instance.collection('users').get().then((value) => uniqueHandler = value.docs.first['userUniqueHandle']);
}
@override
Widget build(BuildContext context) {
return FutureBuilder(
future: fetchUniqueHanlder(),
builder: (context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
// I want to access this one
return Text(uniqueHandler!);
}
return CircularProgressIndicator();
});
}
}
here is the snippet/image of my firebase firestore.
I just wanna access the userUniqueHandler
from my FutureBuilder(page1.dart) to my MainScreen(page2.dart)
the snapshot
itself contains the data:
try this:
Future<QuerySnapshot> fetchUniqueHanlder() async {
return await FirebaseFirestore.instance.collection('users').get();
}
@override
Widget build(BuildContext context) {
return FutureBuilder(
future: fetchUniqueHanlder(),
builder: (context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.connectionState != ConnectionState.done) {
return CircularProgressIndicator();
}
if (snapshot.hasError || !snapshot.hasData) {
return const Text("error");
}
final users = snapshot.data!;
// your value
uniqueHandler = users.docs.first['userUniqueHandle'];
return Text(uniqueHandler!);
},
);
}