NotesWhat is notes.io?

Notes brand slogan

Notes - notes.io

chat_page.dart
import 'dart:io';

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:ichat_app/allConstants/color_constants.dart';
import 'package:ichat_app/allConstants/firestore_constants.dart';
import 'package:ichat_app/allModels/message_chat.dart';
import 'package:ichat_app/allProviders/auth_provider.dart';
import 'package:ichat_app/allProviders/chat_provider.dart';
import 'package:ichat_app/allProviders/settings_provider.dart';
import 'package:ichat_app/allWidgets/loading_view.dart';
import 'package:image_picker/image_picker.dart';
import 'package:intl/intl.dart';
import 'package:provider/src/provider.dart';
import 'package:url_launcher/url_launcher.dart';

import '../main.dart';
import 'full_photo_page.dart';
import 'login_page.dart';

class ChatPage extends StatefulWidget {

final String peerId;
final String peerAvatar;
final String peerNickname;


const ChatPage(
{Key? key, required this.peerId, required this.peerAvatar, required this.peerNickname})
: super(key: key);

@override
State createState() => ChatPageState(
peerId: this.peerId,
peerAvatar: this.peerAvatar,
peerNickname: this.peerNickname,
);
}



class ChatPageState extends State<ChatPage> {

ChatPageState({Key? key, required this.peerId, required this.peerAvatar, required this.peerNickname});

String peerId;
String peerAvatar;
String peerNickname;
late String currentUserId;

List<QueryDocumentSnapshot> listMessage = new List.from([]);

int _limit = 20;
int _limitIncrement = 20;
String groupChatId = "";

File? imageFile;
bool isLoading = false;
bool isShowSticker = false;
String imageUrl = "";

final TextEditingController textEditingController = TextEditingController();
final ScrollController listScrollController = ScrollController();
final FocusNode focusNode = FocusNode();

late ChatProvider chatProvider;
late AuthProvider authProvider;

@override
void initState() {
super.initState();
chatProvider = context.read<ChatProvider>();
authProvider = context.read<AuthProvider>();

focusNode.addListener(onFocusChange);
listScrollController.addListener(_scrollListener);
readLocal();
}

_scrollListener() {
if (listScrollController.offset >=
listScrollController.position.maxScrollExtent &&
!listScrollController.position.outOfRange) {
setState(() {
_limit += _limitIncrement;
});
}
}

void onFocusChange(){
if(focusNode.hasFocus){
setState(() {
isShowSticker = false;
});
}
}

void readLocal(){
if(authProvider.getUserFirebaseId()?.isNotEmpty == true){
currentUserId = authProvider.getUserFirebaseId()!;
}else{
Navigator.of(context).pushAndRemoveUntil(MaterialPageRoute(builder: (context) => LoginPage()),
(Route<dynamic> route) => false,);
}
if(currentUserId.hashCode <= peerId.hashCode){
groupChatId = '$currentUserId-$peerId';
}else{
groupChatId = '$peerId-$currentUserId';
}
chatProvider.updateDataFirestore(
FirestoreConstants.pathUserCollection,
currentUserId,
{FirestoreConstants.chattingWith:peerId}
);






}

Future getImage() async{
ImagePicker imagePicker = ImagePicker();
PickedFile? pickedFile;

pickedFile = await imagePicker.getImage(source: ImageSource.gallery);
if(pickedFile != null){
imageFile = File(pickedFile.path);
if(imageFile != null){
setState(() {
isLoading = true;
});
uploadFile();
}
}



}

void getSticker(){
focusNode.unfocus();
setState(() {
isShowSticker = !isShowSticker;
});
}



Future uploadFile() async{
String fileName = DateTime.now().millisecondsSinceEpoch.toString();
UploadTask uploadTask = chatProvider.uploadFile(imageFile!, fileName);
try{
TaskSnapshot snapshot = await uploadTask;
imageUrl = await snapshot.ref.getDownloadURL();
setState(() {
isLoading = false;
onSendMessage(imageUrl,TypeMessage.image);
});
} on FirebaseException catch (e){
setState(() {
isLoading = false;
});
Fluttertoast.showToast(msg: e.message ?? e.toString());
}
}

void onSendMessage(String content,int type){
if(content.trim().isNotEmpty){
textEditingController.clear();
chatProvider.sendMessage(content, type, groupChatId, currentUserId, peerId);
listScrollController.animateTo(0, duration: Duration(milliseconds: 300), curve: Curves.easeOut);
}else{
Fluttertoast.showToast(msg: 'Gönderilecek bir şey yok', backgroundColor: ColorConstants.greyColor);
}
}

bool isLastMessageLeft(int index){
if((index > 0 && listMessage[index -1].get(FirestoreConstants.idFrom) == currentUserId) || index ==0){
return true;
}else{
return false;
}
}

bool isLastMessageRight(int index){
if((index > 0 && listMessage[index -1].get(FirestoreConstants.idFrom) != currentUserId) || index ==0){
return true;
}else{
return false;
}
}


Future<bool> onBackPress(){
if(isShowSticker){
setState(() {
isShowSticker = false;
});
}else{
chatProvider.updateDataFirestore(
FirestoreConstants.pathUserCollection,
currentUserId,
{FirestoreConstants.chattingWith: null},
);
Navigator.pop(context);
}
return Future.value(false);
}

void _callPhoneNumber(String callPhoneNumber) async{
var url = 'tel://$callPhoneNumber';
if(await canLaunch(url)){
await launch(url);
}else{
throw 'Hata oluştu';
}
}


@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: isWhite? Colors.white : Colors.black,
appBar: AppBar(
backgroundColor: isWhite ? Colors.white : Colors.grey[900],
iconTheme: IconThemeData(
color: ColorConstants.primaryColor,
),
title: Text(
this.peerNickname,
style: TextStyle(color: ColorConstants.primaryColor),
),
centerTitle: true,
actions: <Widget>[
IconButton(
icon: Icon(
Icons.phone_iphone,
size: 30,
color: ColorConstants.primaryColor,
),
onPressed: (){
SettingProvider settingProvider;
settingProvider = context.read<SettingProvider>();
String callPhoneNumber = settingProvider.getPref(FirestoreConstants.phoneNumber) ?? "";
_callPhoneNumber(callPhoneNumber);
},
)
],
),
body: WillPopScope(
child: Stack(
children: <Widget>[
Column(
children: <Widget>[
buildListMessage(),

isShowSticker ? buildSticker() : SizedBox.shrink(),

buildInput(),
],
),
buildLoading()
],
),
onWillPop: onBackPress,
),
);
}

Widget buildSticker(){
return Expanded(
child: Container(
child: Column(
children: <Widget>[
Row(
children: <Widget>[
TextButton(
onPressed: () => onSendMessage('mimi1', TypeMessage.sticker),
child: Image.asset(
'images/mimi1.gif',
width: 50,
height: 50,
fit: BoxFit.cover,
),
),
TextButton(
onPressed: () => onSendMessage('mimi2', TypeMessage.sticker),
child: Image.asset(
'images/mimi2.gif',
width: 50,
height: 50,
fit: BoxFit.cover,
),
),
TextButton(
onPressed: () => onSendMessage('mimi3', TypeMessage.sticker),
child: Image.asset(
'images/mimi3.gif',
width: 50,
height: 50,
fit: BoxFit.cover,
),
),


],
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
),
Row(
children: <Widget>[],
)
],
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
),
decoration: BoxDecoration(
border: Border(top: BorderSide(color: ColorConstants.greyColor2, width: 0.5)), color: Colors.white,
),
padding: EdgeInsets.all(5),
height: 180,
),
);
}



Widget buildLoading(){
return Positioned(
child: isLoading ? LoadingView() : SizedBox.shrink(),
);
}

Widget buildInput(){
return Container(
child: Row(
children: <Widget>[
Material(
child: Container(
margin: EdgeInsets.symmetric(horizontal: 1),
child: IconButton(
icon: Icon(Icons.camera_enhance),
onPressed: getImage,
color: ColorConstants.primaryColor,
),
),
color: Colors.white,
),
Material(
child: Container(
margin: EdgeInsets.symmetric(horizontal: 1),
child: IconButton(
icon: Icon(Icons.face_retouching_natural),
onPressed: getSticker,
color: ColorConstants.primaryColor,
),
),
color: Colors.white,
),
Flexible(
child: Container(
child: TextField(
onSubmitted: (value){
onSendMessage(textEditingController.text, TypeMessage.text);
},
style: TextStyle(color: ColorConstants.primaryColor, fontSize: 15),
controller: textEditingController,
decoration: InputDecoration.collapsed(
hintText: 'Mesajınızı yazın...',
hintStyle: TextStyle(color: ColorConstants.greyColor),
),
focusNode: focusNode,
),
),

),
Material(
child: Container(
margin: EdgeInsets.symmetric(horizontal: 8),
child: IconButton(
icon: Icon(Icons.send),
onPressed: () => onSendMessage(textEditingController.text, TypeMessage.text),
color: ColorConstants.primaryColor,
),
),
color: Colors.white,
),
],
),
width: double.infinity,
height: 50,
decoration: BoxDecoration(
border: Border(top: BorderSide(color: ColorConstants.greyColor2, width: 0.5)), color: Colors.white
),
);
}

Widget buildItem(int index, DocumentSnapshot? document){
if(document != null){
MessageChat messageChat = MessageChat.fromDocument(document);
if(messageChat.idFrom == currentUserId) {
return Row(
children: <Widget>[
messageChat.type == TypeMessage.text
? Container(
child: Text(
messageChat.content,
style: TextStyle(color: ColorConstants.primaryColor),
),
padding: EdgeInsets.fromLTRB(15, 10, 15, 10),
width: 200,
decoration: BoxDecoration(color: ColorConstants.greyColor2,
borderRadius: BorderRadius.circular(8)),
margin: EdgeInsets.only(
bottom: isLastMessageRight(index) ? 20 : 10, right: 10),
) : messageChat.type == TypeMessage.image
? Container(
child: OutlinedButton(
child: Material(
child: Image.network(
messageChat.content,
loadingBuilder: (BuildContext context, Widget child,
ImageChunkEvent? loadingProgress) {
if (loadingProgress == null) return child;
return Container(
decoration: BoxDecoration(
color: ColorConstants.greyColor2,
borderRadius: BorderRadius.all(
Radius.circular(8),
),
),
width: 200,
height: 200,
child: Center(
child: CircularProgressIndicator(
color: ColorConstants.themeColor,
value: loadingProgress.expectedTotalBytes != null &&
loadingProgress.expectedTotalBytes != null
? loadingProgress.cumulativeBytesLoaded /
loadingProgress.expectedTotalBytes!
: null,
),
),
);
},
errorBuilder: (context, object, stackTrace) {
return Material(
child: Image.asset(
'images/img_not_available.jpeg',
width: 200,
height: 200,
fit: BoxFit.cover,
),
borderRadius: BorderRadius.all(
Radius.circular(8),
),
clipBehavior: Clip.hardEdge,
);
},
width: 200,
height: 200,
fit: BoxFit.cover,
),
borderRadius: BorderRadius.all(Radius.circular(8)),
clipBehavior: Clip.hardEdge,
),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => FullPhotoPage(
url: messageChat.content,
)
)
);
},
style: ButtonStyle(padding: MaterialStateProperty.all<EdgeInsets>(EdgeInsets.all(0))),
),
margin: EdgeInsets.only(
bottom: isLastMessageRight(index) ? 20 : 10, right: 10),

) : Container(
child: Image.asset(
'images/${messageChat.content}.gif',
width: 100,
height: 100,
fit: BoxFit.cover,
),
margin: EdgeInsets.only(
bottom: isLastMessageRight(index) ? 20 : 10, right: 10),
),
],
mainAxisAlignment: MainAxisAlignment.end,
);
}else{
return Container(
child: Column(
children: <Widget>[
Row(
children: <Widget>[
isLastMessageLeft(index)
? Material(
child: Image.network(
peerAvatar,
loadingBuilder: (BuildContext context, Widget child, ImageChunkEvent? loadingProgress){
if(loadingProgress == null) return child;
return Center(
child: CircularProgressIndicator(
color: ColorConstants.themeColor,
value: loadingProgress.expectedTotalBytes != null &&
loadingProgress.expectedTotalBytes != null
? loadingProgress.cumulativeBytesLoaded /
loadingProgress.expectedTotalBytes!
: null,
),
);
},
errorBuilder: (context, object, stackTrace){
return Icon(
Icons.account_circle,
size: 35,
color: ColorConstants.greyColor,
);
},
width: 35,
height: 35,
fit: BoxFit.cover,
),
borderRadius: BorderRadius.all(
Radius.circular(18),
),
clipBehavior: Clip.hardEdge,
) : Container(width: 35,),
messageChat.type == TypeMessage.text
? Container(
child: Text(
messageChat.content,
style: TextStyle(color: Colors.white),
),
padding: EdgeInsets.fromLTRB(15, 10, 15, 10),
width: 200,
decoration:
BoxDecoration(color: ColorConstants.primaryColor,borderRadius: BorderRadius.circular(8)),
margin: EdgeInsets.only(left: 10),
) : messageChat.type == TypeMessage.image
? Container(
child: TextButton(
child: Material(
child: Image.network(
messageChat.content,
loadingBuilder: (BuildContext context, Widget child,
ImageChunkEvent? loadingProgress) {
if (loadingProgress == null) return child;
return Container(
decoration: BoxDecoration(
color: ColorConstants.greyColor2,
borderRadius: BorderRadius.all(
Radius.circular(8),
),
),
width: 200,
height: 200,
child: Center(
child: CircularProgressIndicator(
color: ColorConstants.themeColor,
value: loadingProgress.expectedTotalBytes != null &&
loadingProgress.expectedTotalBytes != null
? loadingProgress.cumulativeBytesLoaded /
loadingProgress.expectedTotalBytes!
: null,
),
),
);
},
errorBuilder: (context, object, stackTrace) => Material(
child: Image.asset(
'images/img_not_available.jpeg',
width: 200,
height: 200,
fit: BoxFit.cover,
),
borderRadius: BorderRadius.all(
Radius.circular(8),
),
clipBehavior: Clip.hardEdge,
),
width: 200,
height: 200,
fit: BoxFit.cover,
),
borderRadius: BorderRadius.all(Radius.circular(8)),
clipBehavior: Clip.hardEdge,
),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => FullPhotoPage(url:messageChat.content),
)
);
},
),
margin: EdgeInsets.only(left:10),

) : Container(
child: Image.asset(
'images/${messageChat.content}.gif',
width: 100,
height: 100,
fit: BoxFit.cover,
),
margin :EdgeInsets.only(
bottom: isLastMessageRight(index) ? 20 : 10, right: 10),
),
],
),

isLastMessageLeft(index)
? Container(
child: Text(
DateFormat('dd MMM yyyy, hh:mm a')
.format(DateTime.fromMicrosecondsSinceEpoch(int.parse(messageChat.timestamp))),
style: TextStyle(color: ColorConstants.greyColor, fontSize: 12, fontStyle: FontStyle.italic),
),
margin: EdgeInsets.only(left: 50, top: 5, bottom: 5),
) : SizedBox.shrink()



],
crossAxisAlignment: CrossAxisAlignment.start,
),
margin: EdgeInsets.only(bottom: 10),
);
}
}else{
return SizedBox.shrink();
}
}

Widget buildListMessage(){
return Flexible(
child: groupChatId.isNotEmpty
? StreamBuilder<QuerySnapshot>(
stream: chatProvider.getChatStream(groupChatId, _limit),
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot){
if(snapshot.hasData){
listMessage.addAll(snapshot.data!.docs);
return ListView.builder(
padding: EdgeInsets.all(10),
itemBuilder: (context, index) => buildItem(index, snapshot.data?.docs[index]),
itemCount: snapshot.data?.docs.length,
reverse: true,
controller: listScrollController,
);
}else{
return Center(
child: CircularProgressIndicator(
color: ColorConstants.themeColor,
),
);
}
}
): Center(
child: CircularProgressIndicator(
color: ColorConstants.themeColor,
),
),
);
}


}










     
 
what is notes.io
 

Notes.io is a web-based application for taking notes. You can take your notes and share with others people. If you like taking long notes, notes.io is designed for you. To date, over 8,000,000,000 notes created and continuing...

With notes.io;

  • * You can take a note from anywhere and any device with internet connection.
  • * You can share the notes in social platforms (YouTube, Facebook, Twitter, instagram etc.).
  • * You can quickly share your contents without website, blog and e-mail.
  • * You don't need to create any Account to share a note. As you wish you can use quick, easy and best shortened notes with sms, websites, e-mail, or messaging services (WhatsApp, iMessage, Telegram, Signal).
  • * Notes.io has fabulous infrastructure design for a short link and allows you to share the note as an easy and understandable link.

Fast: Notes.io is built for speed and performance. You can take a notes quickly and browse your archive.

Easy: Notes.io doesn’t require installation. Just write and share note!

Short: Notes.io’s url just 8 character. You’ll get shorten link of your note when you want to share. (Ex: notes.io/q )

Free: Notes.io works for 12 years and has been free since the day it was started.


You immediately create your first note and start sharing with the ones you wish. If you want to contact us, you can use the following communication channels;


Email: [email protected]

Twitter: http://twitter.com/notesio

Instagram: http://instagram.com/notes.io

Facebook: http://facebook.com/notesio



Regards;
Notes.io Team

     
 
Shortened Note Link
 
 
Looding Image
 
     
 
Long File
 
 

For written notes was greater than 18KB Unable to shorten.

To be smaller than 18KB, please organize your notes, or sign in.