Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
172 changes: 126 additions & 46 deletions lib/chatting/chat_page.dart
Original file line number Diff line number Diff line change
@@ -1,30 +1,99 @@
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:signalr_netcore/http_connection_options.dart';
import 'package:signalr_netcore/hub_connection.dart';
import 'package:signalr_netcore/hub_connection_builder.dart';
import 'package:signalr_netcore/ihub_protocol.dart';
import 'package:signalr_netcore/itransport.dart';
import 'package:zoomerm_client/chatting/receiver.dart';
import 'package:zoomerm_client/chatting/service.dart';
import 'package:zoomerm_client/global/global.dart';
import 'package:zoomerm_client/helpers/http_helper.dart';
import 'package:zoomerm_client/models/chatting_model.dart';

class ChattingPage extends StatefulWidget {
const ChattingPage({super.key});
final chatid;
final interlocutor;
ChattingPage({super.key, required this.chatid, required this.interlocutor});

@override
State<ChattingPage> createState() => _ChattingPageState();
}

class _ChattingPageState extends State<ChattingPage> {
ScrollController _scrollController = ScrollController();
List<Items> chattingPage = [];
final TextEditingController _messageController = TextEditingController();
HubConnection? hubConnection;


@override
void initState() {
super.initState();
_initConnection();
}



@override
void dispose() {
hubConnection?.stop();
_messageController.dispose();
super.dispose();
}

Future populateChatting() async {
chattingPage = await ChattingService().getChat("3a7d1341-993e-4981-93a2-03f912c06c97");
List<Items> tempItems = await ChattingService().getChat(widget.chatid);
chattingPage =
tempItems.reversed.toList();
}

void _initConnection() async {
MessageHeaders headers = MessageHeaders();

hubConnection = HubConnectionBuilder()
.withUrl('${HUB_ENDPOINT}?token=${currentLogin?.token}')
.withAutomaticReconnect(retryDelays: [2000, 5000, 10000]).build();

try {
await hubConnection?.start();
hubConnection?.on('newChatMessage', (messageData) {
if (messageData is List<Object?>) {
for (var element in messageData) {
String messageMap = jsonEncode(element);
Items tempItems = new Items(sender: new Sender(userName: widget.interlocutor), content: messageMap);
setState(() {
chattingPage.add(tempItems);
_scrollController.jumpTo(_scrollController.position.minScrollExtent);
});
}
} else {
debugPrint("Invalid message data format: $messageData");
}
});
} catch (e) {
debugPrint('Connection error: $e');
}
}

void sendMessage(String message) async {
if (hubConnection?.state == HubConnectionState.Connected) {
debugPrint("Sent message");
await hubConnection!.invoke('Send',
args: [widget.chatid, message]);
setState(() {
_scrollController.jumpTo(_scrollController.position.minScrollExtent);
});
} else {
debugPrint('Not connected to SignalR');
}
}

@override
Widget build(BuildContext context) {

return Scaffold(
appBar: AppBar(
elevation: 0,
Expand Down Expand Up @@ -61,7 +130,7 @@ class _ChattingPageState extends State<ChattingPage> {
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
"Random Person Name",
widget.interlocutor,
style: TextStyle(fontSize: 16),
),
SizedBox(
Expand All @@ -82,47 +151,47 @@ class _ChattingPageState extends State<ChattingPage> {
body: Stack(
children: <Widget>[
FutureBuilder(
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.none ||
chattingPage.length == 0) {
return Center(child: CircularProgressIndicator());
}
return ListView.builder(
itemCount: chattingPage.length,
shrinkWrap: true,
padding: EdgeInsets.only(top: 10, bottom: 70),
physics: NeverScrollableScrollPhysics(),
itemBuilder: (context, index) {
return Container(
padding: EdgeInsets.only(
left: 14, right: 14, top: 10, bottom: 10),
child: Align(
alignment:
(chattingPage[index].sender?.userName != "ismail"
? Alignment.topLeft
: Alignment.topRight),
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
color:
(chattingPage[index].sender?.userName != "ismail"
? Colors.grey.shade200
: Colors.blue[200]),
),
padding: EdgeInsets.all(16),
child: Text(
chattingPage[index].content.toString(),
style: TextStyle(fontSize: 15),
),
),
),
);
},
);
},
future: populateChatting(),
),

builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.none ||
chattingPage.length == 0) {
return Center(child: CircularProgressIndicator());
}
return ListView.builder(
controller: _scrollController,
itemCount: chattingPage.length,
shrinkWrap: true,
reverse: true,
padding: EdgeInsets.only(top: 10, bottom: 70),
physics: BouncingScrollPhysics(),
itemBuilder: (context, index) {
return Container(
padding: EdgeInsets.only(
left: 14, right: 14, top: 10, bottom: 10),
child: Align(
alignment:
(chattingPage[index].sender?.userName == widget.interlocutor
? Alignment.topLeft
: Alignment.topRight),
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
color: (chattingPage[index].sender?.userName == widget.interlocutor
? Colors.grey.shade200
: Colors.blue[200]),
),
padding: EdgeInsets.all(16),
child: Text(
chattingPage[index].content.toString(),
style: TextStyle(fontSize: 15),
),
),
),
);
},
);
},
future: populateChatting(),
),
Align(
alignment: Alignment.bottomLeft,
child: Container(
Expand All @@ -148,12 +217,12 @@ class _ChattingPageState extends State<ChattingPage> {
),
),
),

SizedBox(
width: 15,
),
Expanded(
child: TextField(
controller: _messageController,
maxLines: null,
decoration: InputDecoration(
hintText: "Write message...",
Expand All @@ -166,7 +235,18 @@ class _ChattingPageState extends State<ChattingPage> {
width: 15,
),
FloatingActionButton(
onPressed: () {},
onPressed: () {
sendMessage(_messageController.text);
setState(() {
Items tempSenderItems = new Items(
content: _messageController.text,
sender: Sender(userName: widget.interlocutor));

chattingPage.add(tempSenderItems);
_messageController.clear();
});

},
child: Icon(
Icons.send,
color: Colors.white,
Expand Down
11 changes: 11 additions & 0 deletions lib/chatting/receiver.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
class MessageDate {
final String content;
final String createdDate;

MessageDate({required this.content, required this.createdDate});

@override
String toString() {
return 'MessageDate{content: $content, createdDate: $createdDate}';
}
}
2 changes: 1 addition & 1 deletion lib/chatting/service.dart
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ class ChattingService extends BlocService<ChattingModel> {

Future<List<Items>> getChat(String uuid) async {
List<Items> charRes = [];
var rs = await HttpHelper.get("${DOMAIN}api/chats/p2p/${uuid}/messages", bearerToken: currentLogin?.token);
var rs = await HttpHelper.get("${DOMAIN}api/chats/p2p/${uuid}/messages?pageSize=1000", bearerToken: currentLogin?.token);
print(await HttpHelper.get("api/chats/p2p/${uuid}/messages", bearerToken: currentLogin?.token));
if (rs.statusCode == 200) {
print("For chatting request 202");
Expand Down
1 change: 1 addition & 0 deletions lib/helpers/http_helper.dart
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import 'package:zoomerm_client/models/login_model.dart';

//const DOMAIN = 'http://localhost:5135'; For developing
const DOMAIN = 'https://localhost:7065/';
const HUB_ENDPOINT = 'https://localhost:7065/hubs/chats/p2p';
const LOGIN_ENDPOINT = DOMAIN + 'login';
class HttpHelper {
static Future<http.Response> post(String url, Map<String, dynamic> body,
Expand Down
3 changes: 0 additions & 3 deletions lib/helpers/login_helper.dart
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,6 @@ class LocalHelper {
static Future<LoginModel?> getAccountFromLocal() async {
SharedPreferences pref = await SharedPreferences.getInstance();
var account = pref.getString('login');
print(account);
print("printing account");
print(account.toString());
if (account != null) {
return LoginModel.fromJson(jsonDecode(account));
}
Expand Down
10 changes: 7 additions & 3 deletions lib/homepage/chat_page.dart
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ class ChatPage extends StatefulWidget {

class _ChatPageState extends State<ChatPage> {
List<ChatModel> chats = [];

@override
void initState() {
// chats = HomePageService().getAllChat();
Expand All @@ -31,7 +31,7 @@ class _ChatPageState extends State<ChatPage> {
}
}
}


@override
Widget build(BuildContext context) {
Expand All @@ -46,8 +46,12 @@ class _ChatPageState extends State<ChatPage> {
return ListView.separated
(itemBuilder: ((context, index) {
return ListTile(

onTap: () {
context.go('/mychats');
context.goNamed('mychats',
pathParameters:
{'chatid': chats[index].id.toString(), 'interl': chats[index].interlocutor!.userName.toString()
});
},
title: Text(chats[index].interlocutor!.userName.toString()),
subtitle: Text('TYT SOOBSHENIYA BUDUT...'),
Expand Down
10 changes: 10 additions & 0 deletions lib/homepage/home_page.dart
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import 'package:zoomerm_client/blocs/login_bloc.dart/service.dart';
import 'package:zoomerm_client/global/global.dart';
import 'package:zoomerm_client/homepage/chat_page.dart';
import 'package:zoomerm_client/homepage/forum_page.dart';
import 'package:zoomerm_client/homepage/search_add_dialog.dart';

class HomePage extends StatefulWidget {
const HomePage({super.key});
Expand Down Expand Up @@ -88,6 +89,15 @@ class _HomePageState extends State<HomePage> {
],
),
),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
hoverColor: Colors.green,
backgroundColor: Colors.red,
foregroundColor: Colors.white,
onPressed: () {
showDialog(context: context, builder: (context) => SearchAndAddDialog());
},
),
bottomNavigationBar: NavigationBar(
onDestinationSelected: (int index) {
setState(() {
Expand Down
67 changes: 67 additions & 0 deletions lib/homepage/search_add_dialog.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import 'package:flutter/material.dart';

class SearchAndAddDialog extends StatefulWidget {
const SearchAndAddDialog({super.key});

@override
State<SearchAndAddDialog> createState() => _SearchAndAddDialogState();
}

class _SearchAndAddDialogState extends State<SearchAndAddDialog> {
final List<String> names = ['ismail', 'Bob', 'Charlie', 'Diana'];
List<String> results = [];
TextEditingController searchController = TextEditingController();
@override
void initState() {
super.initState();
}

@override
void dispose() {
searchController.dispose();
// TODO: implement dispose
super.dispose();
}

@override
Widget build(BuildContext context) {
return AlertDialog(
title: Text("Search user"),
titleTextStyle: TextStyle(fontWeight: FontWeight.bold,
color: Colors.black, fontSize: 20),
actions: [
Row(
children: [
SizedBox(
width: 200,
child: TextFormField(
controller: searchController,
decoration: InputDecoration(
labelText: "put the name or id",
border: OutlineInputBorder()
),
),
),
IconButton(onPressed: (){
for(var temps in names) {
print(searchController.text);
if(temps == searchController.text){
print("Added someone");
setState(() {
debugPrint("Added someone");
results.add(temps);
});
}
}
},
icon: Icon(Icons.search))

],
)
],
content: Card(
child: Text(results.isEmpty ? "No results" : results[0]),
)
);
}
}
Loading