我正在努力避免在新用户注册到应用程序且尚未设置收藏夹时在Method上调用null。
我在两个方法中都放置了一个条件来检索“收藏夹”,以避免方法调用null。
现在,我有另一个错误消息,提到 bool(boolean) 表达式不能为null。我无法解决如何避免这些错误消息。
请注意,正常情况下,用户刚注册时还没有数据。
Future<List<dynamic>> getFavorites() async {
List<dynamic> favorites = await _getFavorites();
// ignore: non_constant_identifier_names
List<String> favorites_documentid = [];
favorites.forEach((reference) {
favorites_documentid.add(reference.documentID);
}
);if (favorites_documentid = null)
return getFavorites();
}
Future<List<dynamic>> _getFavorites() async { // TODO: Use class-wide list that updates only when a a favorite is added or removed. Even listen to a snapshot for this, if there are lots of favorites.
DocumentSnapshot snapshot = await Firestore.instance
.collection('Users').document(_user.uid).get();
if (snapshot.data['favorites'] != null) {
return snapshot.data['favorites'];
// DocumentReference
} else getFavorites();
}
最佳答案
我相信这行中的错误
if (favorites_documentid = null)
它应该是if (favorites_documentid == null)
但这无济于事,因为favorite_documentid永远不会为null,因为它之前已初始化为空List但不为nullList<String> favorites_documentid = [];
您可以检查此列表是否为空if (favorites_documentid.isEmpty) { ... }
最后,当用户没有数据时,似乎出现了无限循环,因为从getFavorites()调用_getFavorites()List<dynamic> favorites = await _getFavorites();
如果_getFavorites()中的数据为null,则称为getFavorites(),依此类推。与getFavorites()相同;
getFavorites() {
...
return getFavorites();
}
如果我正确理解你的话。您需要检索收藏夹ID的列表。Future<List<String>> getFavoritesIds() async {
final List<dynamic> favorites = await _getFavorites();
return favorites.map((reference) => reference.documentID);
}
Future<List<dynamic>> _getFavorites() async {
final DocumentSnapshot snapshot = await Firestore.instance.collection('Users').document(_user.uid).get();
return snapshot?.data['favorites'] ?? [];
}
关于flutter - 调用null和boolean表达式的方法不能为null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65135887/