我在 Flutter 中使用
SwipableStack
包来显示每个用户的图像(与当前登录的不同),然后滑动它们并转到下一个用户图像来滑动并在 SwipableStack 上一一显示他们的个人资料图像。但不知怎的,图像总是一样的。
这是我获取随机用户的函数,它从 Firestore 获取随机用户,然后我使用用户 uid 从存储中获取格式为“uid.jpg”的图像:
Future<DocumentSnapshot?> getRandomUser2({DocumentSnapshot? lastDoc}) async {
try {
final currentUser = FirebaseAuth.instance.currentUser;
final currentUserId = currentUser?.uid;
if (currentUserId == null || currentUserId.isEmpty) {
print("Error: Current user ID is null or empty.");
return null; // Exit early if the user ID is invalid
}
Query query = FirebaseFirestore.instance
.collection('Users')
.where('uid', isNotEqualTo: currentUserId)
.limit(1); // Fetch one user at a time
if (lastDoc != null && lastDoc.exists) {
query = query.startAfterDocument(lastDoc); // Pagination if needed
}
QuerySnapshot querySnapshot = await query.get();
if (querySnapshot.docs.isNotEmpty) {
DocumentSnapshot randomUser = querySnapshot.docs.first;
setState(() {
lastFetchedUser = randomUser; // Update pagination reference
});
String imageUrl = "";
List<String> tempUrls = [];
if (randomUser['uid'] != null && randomUser['uid'].isNotEmpty) {
Reference storageRef = FirebaseStorage.instance
.ref()
.child('user_images')
.child('${randomUser['uid']}.jpg');
try {
imageUrl = await storageRef.getDownloadURL();
print('Fetched image URL: $imageUrl'); // Debug print
tempUrls.add(imageUrl);
} catch (e) {
print('Error fetching image URL for user ${randomUser['uid']}: $e');
}
} else {
print('Invalid or missing UID for the user');
}
// Overwrite the image URL list and reset currentIndexImage
setState(() {
imageUrlList = tempUrls; // Overwrite with new image URL
currentIndexImage = 0; // Reset to zero
isLoading = false; // Update loading state
});
return randomUser; // Return the fetched user
}
} catch (e) {
print('Error fetching user: $e');
}
return null; // Return null if no more users or an error occurred
}
UI 是这样的,但我总是在 Swipable Stack 中得到相同的用户。项目计数始终为 1,以便一次获得一个用户,并且我从 Firebase 存储中获取格式为“uid.jpg”的图像`
@override
Widget build(BuildContext context) {
return Scaffold(
body: Stack(
children: [
if (isLoading) // Show loading indicator if still loading
Center(child: CircularProgressIndicator())
else if (imageUrlList.isNotEmpty)
SwipableStack(
itemCount: 1, // Always show 1 item
builder: (context, properties) {
String imageUrl =
imageUrlList[currentIndexImage]; // Always use index 0
print('Displaying image: $imageUrl'); // Debug print
return ClipRRect(
borderRadius: BorderRadius.circular(60.0),
child: Transform.scale(
scale: 0.95,
child: CachedNetworkImage(
imageUrl: imageUrl,
progressIndicatorBuilder:
(context, url, downloadProgress) =>
CircularProgressIndicator(
value: downloadProgress.progress),
errorWidget: (context, url, error) => Icon(Icons.error),
),
),
);
},
onSwipeCompleted: (index, direction) async {
setState(() {
isLoading =
true; // Show a loading indicator when fetching next user
});
print('Swiped $direction');
await getRandomUser2(lastDoc: lastFetchedUser);
setState(() {
isLoading = false; // Hide loading indicator when done
});
},
)
您正在使用
await storageRef.getDownloadURL()
,然后将其添加到 tempUrls
。但对于大多数 URL,这会在您调用 setState
之后发生,这意味着 UI 不会更新。
要解决此问题,请在添加新的下载 URL 时调用
setState
。例如:
String imageUrl = "";
List<String> tempUrls = [];
if (randomUser['uid'] != null && randomUser['uid'].isNotEmpty) {
Reference storageRef = FirebaseStorage.instance
.ref()
.child('user_images')
.child('${randomUser['uid']}.jpg');
try {
imageUrl = await storageRef.getDownloadURL();
print('Fetched image URL: $imageUrl'); // Debug print
tempUrls.add(imageUrl);
// Overwrite the image URL list and reset currentIndexImage
setState(() {
imageUrlList = tempUrls; // Overwrite with new image URL
currentIndexImage = 0; // Reset to zero
isLoading = false; // Update loading state
});
} catch (e) {
print('Error fetching image URL for user ${randomUser['uid']}: $e');
}
} else {
print('Invalid or missing UID for the user');
}
随着 URL 随着时间的推移进入,这可能会导致一些闪烁,但应该可以解决不显示的问题。