I’m working on a Flutter app where I need to display a list of users from Firestore. When a user taps on a profile, they should be navigated to a chat screen. The chat screen should display the selected user’s profile picture and name in the app bar.
I’ve set up the user list and the chat screen, and I am passing the user data as arguments. However, the chat screen is not displaying the profile picture and name as expected. Here’s what I’ve done so far:
Contacts page screen This page fetches user profiles from the user Profile collection and displays them in a list.
Question How can I ensure that the profile picture and name are correctly passed to and displayed in the Chat Screen’s app bar? Is there anything wrong with how I’m passing the arguments or using them in the Chat Screen?
Thank you for your help!
code of user profile page
import 'dart:io';
import 'package:path/path.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:proguard_86/screens/home_screen.dart'; // Ensure this import is correct
class UserProfile extends StatefulWidget {
static const String screenRoute = "userProfile";
final String email;
const UserProfile({Key? key, required this.email}) : super(key: key);
@override
State<UserProfile> createState() => _UserProfileState();
}
class _UserProfileState extends State<UserProfile> {
File? file;
String? url;
final TextEditingController _nameController = TextEditingController();
var emailcontroller = TextEditingController();
final FirebaseAuth _auth = FirebaseAuth.instance;
Future<void> getImage() async {
final ImagePicker picker = ImagePicker();
final XFile? image = await picker.pickImage(source: ImageSource.gallery);
if (image != null) {
file = File(image.path);
var imageName = basename(image.path);
var refStorage = FirebaseStorage.instance.ref(imageName);
await refStorage.putFile(file!);
url = await refStorage.getDownloadURL();
setState(() {});
}
}
Future<void> saveUserProfile(BuildContext context) async {
String uid = _auth.currentUser!.uid;
if (url != null && _nameController.text.isNotEmpty) {
await FirebaseFirestore.instance
.collection('signup')
.doc(widget.email)
.collection('user_profile')
.doc(uid) // You can use another identifier if needed
.set({
'name': _nameController.text,
'image_link': url,
});
// Navigate to the home screen after saving the profile
Navigator.pushNamed(context, Homescreen.screenroute); // Ensure the correct reference to HomeScreen
} else {
// Handle error, either url or name is not provided
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text("Please provide both name and image."),
backgroundColor: Colors.red,
),
);
}
}
@override
Widget build(BuildContext context) {
//String email=widget.email!;
return Scaffold(
backgroundColor: Colors.red,
appBar: AppBar(
backgroundColor: Colors.red,
title: const Text(
"Profile Info",
style: TextStyle(color: Colors.white),
),
centerTitle: true,
),
body: SingleChildScrollView(
padding: const EdgeInsets.symmetric(horizontal: 20),
child: Column(
children: [
const Text(
"Please provide your name and an optional profile photo",
style: TextStyle(color: Colors.white, fontSize: 12.5),
textAlign: TextAlign.center,
),
const SizedBox(height: 40),
Container(
padding: const EdgeInsets.all(26),
decoration: const BoxDecoration(
shape: BoxShape.circle,
color: Colors.white,
),
child: const Icon(Icons.add_a_photo_rounded),
),
const SizedBox(height: 40),
ElevatedButton(
onPressed: getImage,
child: const Text("Upload Image"),
),
if (url != null)
Image.network(
url!,
width: 100,
height: 100,
fit: BoxFit.fill,
),
Row(
children: [
Expanded(
child: TextFormField(
controller: _nameController,
decoration: const InputDecoration(
hintText: "Type your name here",
),
),
),
const Icon(
Icons.emoji_emotions_outlined,
color: Colors.white,
)
],
),
const SizedBox(height: 20),
ElevatedButton(
onPressed: () => saveUserProfile(context),
child: const Text("Save Profile"),
),
],
),
),
);
}
}
code of individual page
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
class Individualpage extends StatefulWidget {
static const String screenroute = "IndividualPage";
const Individualpage({Key? key}) : super(key: key);
@override
State<Individualpage> createState() => _IndividualpageState();
}
class _IndividualpageState extends State<Individualpage> {
late User? signedInUser;
TextEditingController _messageController = TextEditingController();
@override
void initState() {
super.initState();
getSignedInUser();
}
void getSignedInUser() {
final user = FirebaseAuth.instance.currentUser;
setState(() {
signedInUser = user;
});
}
Future<void> sendMessage(String message, String receiverEmail) async {
try {
if (signedInUser != null) {
final messageData = {
'message': message,
'senderId': signedInUser!.uid,
'senderEmail': signedInUser!.email,
'receiverEmail': receiverEmail, // Add receiver's email
'timestamp': Timestamp.now(),
};
await FirebaseFirestore.instance
.collection('messages')
.add(messageData);
_messageController.clear();
}
} catch (e) {
print('Error sending message: $e');
}
}
@override
Widget build(BuildContext context) {
final routesArguments =
ModalRoute.of(context)?.settings.arguments as Map<String, String>;
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.blue,
leading: CircleAvatar(
child: Text("A"),
),
title: Text("${routesArguments['title']}"),
),
body: Column(
children: [
Expanded(
child: StreamBuilder<QuerySnapshot>(
stream:
FirebaseFirestore.instance.collection('messages').snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return Center(
child:
CircularProgressIndicator(backgroundColor: Colors.blue),
);
}
final messages = snapshot.data!.docs;
return ListView.builder(
itemCount: messages.length,
itemBuilder: (context, index) {
final message = messages[index];
final messageText = message['message'];
final senderId = message['senderId'];
final isMe = signedInUser?.uid == senderId;
return MessageReplay(
sendmessage: messageText,
isMe: isMe,
);
},
);
},
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
children: [
Expanded(
child: TextField(
controller: _messageController,
decoration: InputDecoration(
hintText: 'Type a message...',
),
),
),
IconButton(
icon: Icon(Icons.send),
onPressed: () {
final message = _messageController.text.trim();
final receiverEmail =
'[email protected]'; // Replace with the receiver's email address
if (message.isNotEmpty) {
sendMessage(message, receiverEmail);
}
},
),
],
),
),
],
),
// bottomSheet: BottomSendNotification(),
);
}
}
class MessageReplay extends StatelessWidget {
final String? sendmessage;
final bool isMe;
const MessageReplay({Key? key, this.sendmessage, required this.isMe})
: super(key: key);
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(10.0),
child: Column(
crossAxisAlignment:
isMe ? CrossAxisAlignment.end : CrossAxisAlignment.start,
children: [
Material(
elevation: 5,
borderRadius: BorderRadius.only(
topLeft: Radius.circular(30),
bottomLeft: isMe ? Radius.circular(30) : Radius.circular(0),
bottomRight: isMe ? Radius.circular(0) : Radius.circular(30),
topRight: Radius.circular(30),
),
color: isMe ? Colors.blue : Colors.white,
child: Padding(
padding: const EdgeInsets.all(12.0),
child: Text(
sendmessage ?? 'Message not found', // Handle null message
style: TextStyle(
fontSize: 15, color: isMe ? Colors.white : Colors.black),
),
),
),
],
),
);
}
}
Problem Even though I’m passing the arguments correctly, the profile picture and name are not displayed in the ChatScreen’s app bar.
Expected Behavior When a user taps on a profile in the UserListPage, they should be navigated to the ChatScreen. The ChatScreen should display the selected user’s profile picture and name in the app bar. Actual Behavior The app navigates to the ChatScreen, but the app bar does not show the profile picture and name as expected.
RA227 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.