问题
Trying to retrieve the authenticated user details from the existing Firestore user document, I get the following error:
The getter 'uid' was called on null
my code is as follows:
class SideDrawer extends StatelessWidget {
const SideDrawer({Key key, this.user}) : super(key: key);
final FirebaseUser user;
@override
Widget build(BuildContext context) {
return ......
......
userPanel(context),
......
}
Widget userPanel(BuildContext context) {
return new Padding(
padding: const EdgeInsets.only(top: 10.0),
child: new DrawerHeader(
child: StreamBuilder<DocumentSnapshot>(
stream: Firestore.instance
.collection('users')
.document(user.uid)
.snapshots(),
builder:
(BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot) {
if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
} else if (snapshot.hasData) {
return userName(snapshot.data);
}
return LinearProgressIndicator();
},
),
),
);
}
}
Text userName(DocumentSnapshot snapshot) {
if (snapshot.data == null) {
return Text('no data set in the user document in firestore');
} else {
return snapshot.data['name'];
}
}
sending user from login page:
void signIn() async {
if(_formKey.currentState.validate()){
_formKey.currentState.save();
try{
FirebaseUser user = await FirebaseAuth.instance.signInWithEmailAndPassword(email: _email, password: _password);
Navigator.push(context, MaterialPageRoute(builder: (context) => HomePage(user: user)));
}catch(e){
print(e.message);
}
}
}
}
and here is my Home page:
class HomePage extends StatelessWidget {
const HomePage({Key key, this.user}) : super(key: key);
final FirebaseUser user;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Home'),
),
drawer: SideDrawer(),
);
}
}
Guessing this is an asynchronous programming issue, I did some search on it and found few solutions using "Future" object but could not figure out how to implement it in a correct way, any help please ?
回答1:
If you are using Future
I guess when you call SideDrawer
the user is null, so you have to add a validation before you can use 'user' object.
Widget userPanel(BuildContext context) {
return new Padding(
padding: const EdgeInsets.only(top: 10.0),
child: user != null ? DrawerHeader(
child: StreamBuilder<DocumentSnapshot>(
stream: Firestore.instance
.collection('users')
.document(user.uid)
.snapshots(),
builder:
(BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot) {
if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
} else if (snapshot.hasData) {
return userName(snapshot.data);
}
return LinearProgressIndicator();
},
),
) : Center(child: CircularProgressIndicator(),)
);
}
Pass the user object on your SideDrawer widget from HomePage
SideDrawer(user: user),
Also fix this line:
return snapshot.data['name'];
It should be :
return Text(snapshot.data['name']);
来源:https://stackoverflow.com/questions/54244652/flutter-how-to-return-current-user-from-firestore