Skip to content

Commit

Permalink
Merge pull request #7 from D-extremity/backend
Browse files Browse the repository at this point in the history
app completed
  • Loading branch information
D-extremity authored Oct 30, 2023
2 parents 1bf1bfc + 148520b commit 9737bc4
Show file tree
Hide file tree
Showing 4 changed files with 197 additions and 39 deletions.
49 changes: 49 additions & 0 deletions lib/authorization/chatservice.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import 'package:chatapp/models/chatmodel.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';

class ChatService {
final FirebaseAuth _auth = FirebaseAuth.instance;
final FirebaseFirestore _firestore = FirebaseFirestore.instance;

//! Send Message
Future<void> sendMessage(
{required String recieverId, required String message}) async {
//& Get Current User Info
final String currentUserId = _auth.currentUser!.uid;
final String currentUserEmail = _auth.currentUser!.email.toString();
final Timestamp timeStamp = Timestamp.now();
//& Create New Message

Message newMessage = Message(
senderId: currentUserId,
recieverId: recieverId,
message: message,
senderEmail: currentUserEmail,
timeStamp: timeStamp);
//& Construct chat room id from senderId and recieverId (sort senderId and recieverId then create chatRoomId to avoid two different chatrooms for a single conversation room )
List<String> ids = [currentUserId, recieverId];
ids.sort();
final String chatRoomId = ids.join('_');
//& add new message to database
await _firestore
.collection('Chat Rooms')
.doc(chatRoomId)
.collection('messages')
.add(newMessage.toMap());
}

//& get Messages
Stream<QuerySnapshot> getMessages(
{required String userId, required String otherUserId}) {
List<String> ids = [userId, otherUserId];
ids.sort();
final String chatRoomId = ids.join('_');
return _firestore
.collection('Chat Rooms')
.doc(chatRoomId)
.collection('messages')
.orderBy('timeStamp', descending: false)
.snapshots();
}
}
32 changes: 32 additions & 0 deletions lib/models/chatmodel.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
// ignore_for_file: public_member_api_docs, sort_constructors_first
import 'dart:convert';

import 'package:cloud_firestore/cloud_firestore.dart';

class Message {
final String senderId;
final String recieverId;
final String message;
final String senderEmail;
final Timestamp timeStamp;

Message({
required this.senderId,
required this.recieverId,
required this.message,
required this.senderEmail,
required this.timeStamp,
});

Map<String, dynamic> toMap() {
return <String, dynamic>{
'senderId': senderId,
'recieverId': recieverId,
'message': message,
'senderEmail': senderEmail,
'timeStamp': timeStamp,
};
}


}
120 changes: 91 additions & 29 deletions lib/pages/messaging.dart
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
// import 'dart:isolate';

import 'package:chatapp/authorization/chatservice.dart';
import 'package:chatapp/utils/color.dart';
import 'package:chatapp/widget/chatwidget.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';

class Messaging extends StatefulWidget {
Expand All @@ -19,6 +24,18 @@ class _MessagingState extends State<Messaging> {
super.initState();
}

final TextEditingController _messageController = TextEditingController();
final ChatService _chatService = ChatService();
// final FirebaseAuth _auth = FirebaseAuth.instance;
void sendMessage() async {
if (_messageController.text.trim().isNotEmpty) {
await _chatService.sendMessage(
recieverId: widget.otherPersonId, message: _messageController.text);
//! cleaning the controller
_messageController.clear();
}
}

@override
Widget build(BuildContext context) {
final size = MediaQuery.of(context).size;
Expand All @@ -37,7 +54,7 @@ class _MessagingState extends State<Messaging> {
padding: const EdgeInsets.only(right: 8, left: 8),
child: ListView(children: [
Container(
height: size.height * 0.8,
height: size.height * 0.75,
width: double.infinity,
// ! child: , Column will come here to show chats
// color: Colors.deepPurple.shade200.withOpacity(0.2),
Expand All @@ -52,45 +69,90 @@ class _MessagingState extends State<Messaging> {
const Color.fromARGB(255, 210, 13, 228).withOpacity(0.1),
Colors.pink.withOpacity(0.2),
])),
child: Column(crossAxisAlignment: CrossAxisAlignment.start,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
ChatWidget(size: size,isMyChat: false,chat: "Satyam is my name heres the first chat",),
Expanded(child: _buildMessageList(size))
// ChatWidget(
// size: size,
// isMyChat: false,
// chat: " Satyam is my name heres the first chat",
// ),
],
),
),
Expanded(
child: Align(
alignment: Alignment.bottomCenter,
child: TextField(
onTapOutside: (event) =>
FocusScope.of(context).requestFocus(FocusNode()),
style: const TextStyle(fontSize: 20),
canRequestFocus: true,
decoration: InputDecoration(
suffixIcon: IconButton(
icon: Icon(
Icons.send,
size: 40,
color: Colors.blueGrey.shade900,
),
onPressed: () {}, //! send chat
),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(30),
SizedBox(
height: size.height * 0.05,
),
Align(
alignment: Alignment.bottomCenter,
child: TextField(
onTapOutside: (event) =>
FocusScope.of(context).requestFocus(FocusNode()),
style: const TextStyle(fontSize: 20),
controller: _messageController,
canRequestFocus: true,
decoration: InputDecoration(
suffixIcon: IconButton(
icon: Icon(
Icons.send,
size: 40,
color: Colors.blueGrey.shade900,
),
fillColor: Colors.deepPurple,
filled: true,
hintText: "Yeah , why not..",
onPressed: () {
sendMessage();
}, //! send chat
),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(30),
),
fillColor: Colors.deepPurple,
filled: true,
hintText: "Yeah , why not..",
),
),
),
const SizedBox(
height: 10,
)

]),
),
));
}
}

Widget _buildMessageList(final size) {
return StreamBuilder(
stream: _chatService.getMessages(
userId: FirebaseAuth.instance.currentUser!.uid,
otherUserId: widget.otherPersonId),
builder: (context, snapshot) {
if (snapshot.hasError) {
return Text("Error : ${snapshot.error}");
}
if (snapshot.connectionState == ConnectionState.waiting) {
return const CircularProgressIndicator();
}

return ListView(
children: snapshot.data!.docs
.map((document) => _buildMessageItem(document,size))
.toList(),
);
});
}

Widget _buildMessageItem(DocumentSnapshot document, final size) {
Map<String, dynamic> data = document.data() as Map<String, dynamic>;
var alignment =
(data['senderId'] == FirebaseAuth.instance.currentUser!.uid.toString()
? Alignment.centerRight
: Alignment.centerLeft);
bool isMyChat =
(data['senderId'] == FirebaseAuth.instance.currentUser!.uid.toString());
return ChatWidget(
size: size,
chat: data['message'],
isMyChat: isMyChat,
alignment: alignment,
otherPersonName: widget.otherPersonName,
senderName: "You",);
}
}
35 changes: 25 additions & 10 deletions lib/widget/chatwidget.dart
Original file line number Diff line number Diff line change
@@ -1,15 +1,20 @@
import 'package:flutter/material.dart';

class ChatWidget extends StatefulWidget {
final bool isMyChat;
final bool isMyChat;
final String chat;
final Alignment alignment;
final String otherPersonName;
final String senderName;

const ChatWidget({
super.key,
required this.size,
required this.chat,
required this.isMyChat,
});
const ChatWidget(
{super.key,
required this.senderName,
required this.size,
required this.chat,
required this.isMyChat,
required this.alignment,
required this.otherPersonName});

final Size size;

Expand All @@ -21,6 +26,8 @@ class _ChatWidgetState extends State<ChatWidget> {
@override
Widget build(BuildContext context) {
return Container(
margin: const EdgeInsets.all(10),
alignment: widget.alignment,
width: widget.size.width * 0.45,
decoration: BoxDecoration(
shape: BoxShape.rectangle,
Expand All @@ -42,9 +49,17 @@ class _ChatWidgetState extends State<ChatWidget> {
const Color.fromARGB(255, 57, 194, 86).withOpacity(0.1),
]),
),
child: Text(
widget.chat,
style: const TextStyle(fontSize: 20, color: Colors.white),
child: Column(
children: [
Text(
widget.isMyChat?widget.senderName: widget.otherPersonName,
style: const TextStyle(fontSize: 10),
),
Text(
widget.chat,
style: const TextStyle(fontSize: 20, color: Colors.white),
),
],
),
);
}
Expand Down

0 comments on commit 9737bc4

Please sign in to comment.