skip to Main Content

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

2

Answers


  1. You can upload a dummy image to firebase Firestore then on chat screen you can check if user image is empty pass the url of the dummy image you have uploaded on the firebase.

    Login or Signup to reply.
  2. To display a user’s profile picture and name in the AppBar, create a row with a CircleAvatar for the photo and a Text widget for the name. Retrieve the user data from a data source (such as Firebase) and pass it to the AppBar. This personalized touch improves the user experience and strengthens the identity of your chat app.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search