I am new in flutter app. I have made a subcollection products in users collections. It will show to all when a user will log in to their account. When the user clicks on the My Products button it will only show those products which are created by the login user. I user stream builder and use this FirebaseFirestore.instance .collection('users') .doc(LoginUser!.uid) .collection('products') .snapshots() , to get the data. But when I click on the button it throws an exception. Which provide on the screen shots.
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
class UserProductList extends StatefulWidget {
UserProductList({Key? key}) : super(key: key);
@override
_UserProductListState createState() => _UserProductListState();
}
class _UserProductListState extends State<UserProductList> {
User? LoginUser;
@override
void initState() {
super.initState();
getCurrentUser();
}
void getCurrentUser() async{
var LoginUser=await FirebaseAuth.instance.currentUser;
print(LoginUser!.email);
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: StreamBuilder(
stream: FirebaseFirestore.instance
.collection('users')
.doc(LoginUser!.uid)
.collection('products')
.snapshots() ,
builder:(BuildContext, AsyncSnapshot<QuerySnapshot<Map<String, dynamic>>> snapshot){
return ListView(
children: snapshot.data!.docs.map((document){
return ElevatedButton(onPressed: getCurrentUser, child: Text('data'));
}).toList(),
);
},
),
);
}
}
CodePudding user response:
FIrst of all, FirebaseAuth.instance.currentUser
is not a Future
it doesn't need to be await
ed. You can use it straight away in your StreamBuilder
.doc(FirebaseAuth.instance.currentUser?.uid ?? '')
CodePudding user response:
My mistake was by making the currentUser future by using async and await. that's why steamBulder did not get the user id to fetch the data and throwing error for null user.
void getCurrentUser() async{
var LoginUser=await FirebaseAuth.instance.currentUser;
print(LoginUser!.email);
}```
So, I just remove this portion code and instead of that I just use this **var LoginUser = FirebaseAuth.instance.currentUser;** to get my **login user Uid** and it's working perfectly