@override
Widget build(BuildContext context) {
final user = Provider.of<User>(context);
return StreamBuilder<UserData>(
stream: DatabaseService(uid: user.uid).currentUserData,
builder: (context, snapshot) {
print(snapshot.data); // return null
DatabaseService类
class DatabaseService {
final String uid;
DatabaseService({this.uid});
//collection reference
CollectionReference userCollection = Firestore.instance.collection('user');
//get user data stream
Stream<UserData> get currentUserData {
return userCollection.document(uid).snapshots().map(_userDataFromSnapshot);
}
//user data from snapshot
UserData _userDataFromSnapshot(DocumentSnapshot snapshot) {
return UserData(
uid: snapshot.data['uid'],
email: snapshot.data['email'],
fName: snapshot.data['first_name'],
lName: snapshot.data['last_name'],
mobileNumber: snapshot.data['mobile_number'],
gender: snapshot.data['gender'],
dob: snapshot.data['date_of_birth'],
);
}
}
我希望获取的数据是我调用的对象的实例。
它返回flutter: null
。
当我在练习应用中尝试时,它返回I/flutter (11395): Instance of 'UserData'
我不知道问题出在哪里,请帮忙。我是Flutter的新手。
答案 0 :(得分:0)
在使用Streams
时,可能在窗口小部件渲染时尚未获取任何数据。因此,在尝试访问如下数据之前,我们需要检查流的状态
if (snapshot.hasError){
// access error using snapshot.error
}
else{
// check for stream state
switch (snapshot.connectionState) {
case ConnectionState.none:
case ConnectionState.waiting:
case ConnectionState.active: // access snapshot.data in this case
case ConnectionState.done:
}
}
有关更多参考,您可以查看StreamBuilder
的文档