延迟初始化错误:字段'user'尚未初始化



用户初始值有问题。

我有这种类型的源代码:"https://paste.ofcode.org/ycHT4YFsDGSQXa68JiKJRH">

链接中的重要行:

child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
height: 240,
child: FutureBuilder(
future: getCurrentUser(),
builder: (context, snapshot) {
return ListView.separated(
itemBuilder: (context, index) {
print(index);
return GetUserName(documentId: user?.uid);
},
separatorBuilder: (context, index) {
return SizedBox(width: 10);
},
itemCount: myCards.length,
shrinkWrap: true,
scrollDirection: Axis.horizontal,
);
}),

我也有这个类,

class GetUserName extends StatelessWidget {
final String documentId;
final int index = 0;
GetUserName({
required this.documentId,
});
@override
Widget build(BuildContext context) {
// get the collection
CollectionReference users = FirebaseFirestore.instance.collection('Users');
return FutureBuilder<DocumentSnapshot>(
future: users.doc(documentId).get(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
Map<String, dynamic> data =
snapshot.data!.data() as Map<String, dynamic>;
return MyCard(
userName: data['username'],
card: myCards[index],
);
//  Text('First Name: ${data['username']}');
} else {
print("here");
return MyCard(
userName: "Waiting",
card: myCards[index],
);
}
return Text('loading..');
},
);
}
}

我在90th行使用FutureBuilder,它的未来值是getCurrentUser(),这个函数创建这个值user = await _auth.currentUser;

,我给用户?第96行GetUserName函数的uid参数(目的:将当前用户id赋给GetUserName)

我在MyCard中成功看到当前用户名,但我也出现了错误

======== Exception caught by widgets library =======================================================
The following LateError was thrown building:
LateInitializationError: Field 'user' has not been initialized.

如何解决这个问题?

使用User? user代替late final user,以便能够在用户加载之前检查空值。在getCurrentUser()方法中,当获取用户时,使用setState来更新用户和当前状态:

Future getCurrentUser() async {
final loadedUser = await _auth.currentUser;
if (loadedUser != null) {
setState(() {
user = loadedUser;
});
}
}

最新更新