How to Display User Profile Image and Name in AppBar of Chat Screen in Flutter?

I’m building a Flutter app where users can chat with each other. I have implemented user authentication and can store user profile information such as the profile image link and name in Firestore. Now, I want to display the user’s profile image and name in the AppBar of the chat screen.Requirements:

Store Profile Data: I have stored user profile information (image link and name) in Firestore.
Retrieve Profile Data: I need to retrieve this data and display it in the AppBar of the chat screen.

ChatScreen
This page is supposed to display the selected user’s profile picture and name in the app bar.

import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';

class ChatScreen extends StatefulWidget {
  static const String screenRoute = "ChatScreen";
  const ChatScreen({Key? key}) : super(key: key);

  @override
  State<ChatScreen> createState() => _ChatScreenState();
}

class _ChatScreenState extends State<ChatScreen> {
  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,
          '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 routeArguments = ModalRoute.of(context)?.settings.arguments as Map<String, String>;

    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.blue,
        leading: CircleAvatar(
          backgroundImage: NetworkImage(routeArguments['imageLink'] ?? ''),
        ),
        title: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(routeArguments['title'] ?? ''),
            Text(
              'Last seen: ${routeArguments['lastSeen'] ?? ''}',
              style: TextStyle(fontSize: 12),
            ),
          ],
        ),
      ),
      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 = routeArguments['email'] ?? '';
                    if (message.isNotEmpty && receiverEmail.isNotEmpty) {
                      sendMessage(message, receiverEmail);
                    }
                  },
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}

class MessageReplay extends StatelessWidget {
  final String sendMessage;
  final bool isMe;

  const MessageReplay({Key? key, required 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,
                style: TextStyle(
                  fontSize: 15,
                  color: isMe ? Colors.white : Colors.black,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}

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"),
            ),
          ],
        ),
      ),
    );
  }
}

Questions:

Fetching Data Efficiently: Is there a more efficient way to fetch and display the user’s profile data in the AppBar?
Handling Errors: How should I handle cases where the user data might not be available or the image URL is invalid?
Updating Profile: If the user’s profile data changes, will the AppBar automatically update, or do I need to implement additional logic to handle real-time updates?
UI/UX Best Practices: Are there any best practices for displaying user profile information in the AppBar that I should consider?

I need to retrieve this data and display it in the AppBar of the chat screen

New contributor

AhmedHussien888 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật