Advertisement
Guest User

Untitled

a guest
Feb 22nd, 2022
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.92 KB | None | 0 0
  1. import 'package:cloud_firestore/cloud_firestore.dart';
  2. import 'package:firebase_auth/firebase_auth.dart';
  3. import 'package:flutter/cupertino.dart';
  4. import 'package:flutter/material.dart';
  5. import 'package:flutter_chat_bubble/bubble_type.dart';
  6. import 'package:flutter_chat_bubble/chat_bubble.dart';
  7. import 'package:flutter_chat_bubble/clippers/chat_bubble_clipper_6.dart';
  8.  
  9. class ChatDetail extends StatefulWidget {
  10. final friendUid;
  11. final friendName;
  12.  
  13. const ChatDetail({Key? key, this.friendUid, this.friendName})
  14. : super(key: key);
  15.  
  16. @override
  17. _ChatDetailState createState() => _ChatDetailState(friendUid, friendName);
  18. }
  19.  
  20. class _ChatDetailState extends State<ChatDetail> {
  21. CollectionReference chats = FirebaseFirestore.instance.collection('chats');
  22. final friendUid;
  23. final friendName;
  24. final currentUserId = FirebaseAuth.instance.currentUser!.uid;
  25. var chatDocId;
  26. var _textController = new TextEditingController();
  27.  
  28. _ChatDetailState(this.friendUid, this.friendName);
  29.  
  30. @override
  31. void initState() {
  32. super.initState();
  33. chats
  34. .where('users', isEqualTo: {friendUid: null, currentUserId: null})
  35. .limit(1)
  36. .get()
  37. .then((QuerySnapshot querySnapshot) {
  38. if (querySnapshot.docs.isNotEmpty) {
  39. chatDocId = querySnapshot.docs.single.id;
  40. } else {
  41. chats.add({
  42. 'users': {currentUserId: null, friendUid: null}
  43. }).then((value) => {chatDocId = value});
  44. }
  45. })
  46. .catchError((error) {});
  47. }
  48.  
  49. void sendMessage(String msg) {
  50. if (msg == '') return;
  51. chats.doc(chatDocId).collection('messages').add({
  52. 'createdOn': FieldValue.serverTimestamp(),
  53. 'uid': currentUserId,
  54. 'msg': msg
  55. }).then((value) {
  56. _textController.text = '';
  57. });
  58. }
  59.  
  60. bool isSender(String friend) {
  61. return friend == currentUserId;
  62. }
  63.  
  64. Alignment getAlignment(friend) {
  65. if (friend == currentUserId) {
  66. return Alignment.topRight;
  67. }
  68. return Alignment.topLeft;
  69. }
  70.  
  71. @override
  72. Widget build(BuildContext context) {
  73. return StreamBuilder<QuerySnapshot>(
  74. stream: FirebaseFirestore.instance
  75. .collection("chats")
  76. .doc(chatDocId)
  77. .collection('messages')
  78. .orderBy('createdOn', descending: true)
  79. .snapshots(),
  80. builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
  81. if (snapshot.hasError) {
  82. return Center(
  83. child: Text("Error"),
  84. );
  85. }
  86. if (snapshot.connectionState == ConnectionState.waiting) {
  87. return Scaffold(
  88. backgroundColor: Colors.indigo.shade50,
  89. );
  90. }
  91. if (snapshot.hasData) {
  92. var data;
  93. return Container(
  94. decoration: BoxDecoration(
  95. image: DecorationImage(
  96. image: AssetImage("assets/images/chatscreen.png"),
  97. fit: BoxFit.cover,
  98. )),
  99. child: CupertinoPageScaffold(
  100. backgroundColor: Colors.transparent,
  101. navigationBar: CupertinoNavigationBar(
  102. previousPageTitle: "Back",
  103. middle: Text(friendName),
  104. trailing: CupertinoButton(
  105. padding: EdgeInsets.zero,
  106. onPressed: () {},
  107. child: Icon(Icons.person),
  108. ),
  109. ),
  110. child: SafeArea(
  111. child: Column(
  112. children: [
  113. Expanded(
  114. child: ListView(
  115. reverse: true,
  116. children: snapshot.data!.docs
  117. .map((DocumentSnapshot document) {
  118. data = document.data()!;
  119.  
  120. return Padding(
  121. padding:
  122. const EdgeInsets.symmetric(horizontal: 8.0),
  123. child: ChatBubble(
  124. clipper: ChatBubbleClipper6(
  125. nipSize: 0,
  126. radius: 0,
  127. type: BubbleType.receiverBubble,
  128. ),
  129. alignment: getAlignment(data['uid'].toString()),
  130. margin: EdgeInsets.only(top: 20),
  131. backGroundColor: isSender(data['uid'].toString())
  132. ? Color(0xFF08C187)
  133. : Color(0xffE7E7ED),
  134. child: Container(
  135. constraints: BoxConstraints(
  136. maxWidth:
  137. MediaQuery.of(context).size.width * 0.7,
  138. ),
  139. child: Column(
  140. children: [
  141. Row(
  142. mainAxisAlignment:
  143. MainAxisAlignment.start,
  144. children: [
  145. Text(
  146. data['msg'],
  147. style: TextStyle(
  148. color: isSender(
  149. data['uid'].toString())
  150. ? Colors.white
  151. : Colors.black),
  152. maxLines: 100,
  153. overflow: TextOverflow.ellipsis,
  154. )
  155. ],
  156. ),
  157. Row(
  158. mainAxisAlignment: MainAxisAlignment.end,
  159. children: [
  160. Text(
  161. data['createdOn'] == null
  162. ? DateTime.now().toString()
  163. : data['createdOn']
  164. .toDate()
  165. .toString(),
  166. style: TextStyle(
  167. fontSize: 10,
  168. color: isSender(
  169. data['uid'].toString())
  170. ? Colors.white
  171. : Colors.black)),
  172. ],
  173. )
  174. ],
  175. ),
  176. ),
  177. ),
  178. );
  179. }).toList(),
  180. )),
  181. Row(
  182. mainAxisAlignment: MainAxisAlignment.spaceEvenly,
  183. children: [
  184. Expanded(
  185. child: CupertinoTextField(
  186. controller: _textController,
  187. )),
  188. CupertinoButton(
  189. onPressed: () =>
  190. sendMessage(_textController.text),
  191. child: Icon(
  192. Icons.send_sharp,
  193. ))
  194. ],
  195. )
  196. ],
  197. ),
  198. )),
  199. );
  200. }
  201. return Container();
  202. },
  203. );
  204. }
  205. }
  206.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement