Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: 💬chat-feature using firebase #43

Closed
wants to merge 1 commit into from
Closed
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
156 changes: 156 additions & 0 deletions lib/directory/chat_screen.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:intl/intl.dart';
import 'package:timeago/timeago.dart' as timeago;

class ChatScreen extends StatefulWidget {
static const routeName = '/ChatScreen';

@override
_ChatScreenState createState() => _ChatScreenState();
}

class _ChatScreenState extends State<ChatScreen> {
final TextEditingController textEditingController = TextEditingController();
final FirebaseAuth auth = FirebaseAuth.instance;
final ScrollController _scrollController = ScrollController();

void onSendMessage(String content) async {

if (content.trim() != '') {
textEditingController.clear();

final user = auth.currentUser.email;
CollectionReference messages =
FirebaseFirestore.instance.collection('messages');

await messages
.add({'content': content, 'by': user, 'time': DateTime.now()});

_scrollController.animateTo(0.0, duration: Duration(milliseconds: 300), curve: Curves.easeOut);
} else {
Fluttertoast.showToast(msg: 'Nothing to send!');
}
}

Widget futureBuilder() {
return StreamBuilder(
stream: FirebaseFirestore.instance
.collection('messages')
.orderBy('time', descending: false)
.snapshots(),
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
return Center(
heightFactor: 10,
widthFactor: 10,
child: CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation(Colors.indigo[600]),
),
);

case ConnectionState.waiting:
return Center(
child: CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation(Colors.indigo[600]),
),
);

default:
if (snapshot.hasError)
return new Text('Error: ${snapshot.error}');
else
return new ListView.builder(
controller: _scrollController,
itemCount: snapshot.data.docs.length,
itemBuilder: (BuildContext context, int index) {
DocumentSnapshot doc = snapshot.data.docs[index];
return new ListTile(
title: Text(
doc["by"],
textAlign: TextAlign.left,
style: TextStyle(
fontSize: 12.0, color: Colors.grey[500]),
),
subtitle: Text(
doc["content"],
textAlign: TextAlign.left,
style: TextStyle(
color: Colors.indigo[700],
fontSize: 18.0),
),
trailing: Text(
timeago.format(doc["time"].toDate()),
style: TextStyle(
fontSize: 12.0, color: Colors.grey[500]),
),
contentPadding: EdgeInsets.symmetric(
horizontal: 15.0, vertical: 4.0),
);
});
}
});
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.indigo[700],
title: Text("Chat"),
),
body: Stack(
children: <Widget>[
futureBuilder(),
Align(
alignment: Alignment.bottomLeft,
child: Container(
padding: EdgeInsets.only(left: 10, bottom: 10, top: 10),
height: 60,
width: double.infinity,
color: Colors.white,
child: Row(
children: <Widget>[
SizedBox(
width: 15,
),
Expanded(
child: TextField(
controller: textEditingController,
decoration: InputDecoration(
hintText: "Type your message here..",
hintStyle: TextStyle(color: Colors.grey),
border: InputBorder.none),
),
),
SizedBox(
width: 15,
),
FloatingActionButton(
onPressed: () {
setState(() {
onSendMessage(textEditingController.text);
});
},
child: Icon(
Icons.send,
color: Colors.white,
size: 18,
),
backgroundColor: Colors.indigo[700],
elevation: 0,
),
],
),
),
),
],
),
);
}
}
93 changes: 48 additions & 45 deletions lib/directory/directory.dart
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:campusbuddy/directory/blank.dart';
import 'directory_list_widget.dart';

import 'chat_screen.dart';
class Directory extends StatefulWidget {
Directory({Key key}) : super(key: key);

Expand All @@ -15,79 +15,82 @@ class Directory extends StatefulWidget {
}

class _DirectoryState extends State<Directory> {
int _currentIndex=0;
int _currentIndex = 0;
final _selectedBgColor = Colors.indigo[900];
final _unselectedBgColor = Colors.indigo[700];
final List<Widget> _children =[
final List<Widget> _children = [
DirectoryList(),
PostList(),
//Blank()
Blank()
];

void onTabTapped(int index){
void onTabTapped(int index) {
setState(() {
_currentIndex=index;
_currentIndex = index;
});
}

Color _getBgColor(int index)=>
_currentIndex==index ? _selectedBgColor:_unselectedBgColor;
Color _getBgColor(int index) =>
_currentIndex == index ? _selectedBgColor : _unselectedBgColor;

Widget _buildIcon(IconData iconData, String text, int index)=>
Container(
Widget _buildIcon(IconData iconData, String text, int index) => Container(
width: double.infinity,
height: kBottomNavigationBarHeight,
child: InkWell(
onTap: ()=>onTabTapped(index),
onTap: () => onTabTapped(index),
child: Material(
color: _getBgColor(index),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Icon(iconData,color: Colors.white,),
Text(text,style: TextStyle(color: Colors.white,
fontFamily: 'Roboto'))
Icon(
iconData,
color: Colors.white,
),
Text(text,
style: TextStyle(color: Colors.white, fontFamily: 'Roboto'))
],
),
),
),
);



@override
Widget build(BuildContext context) {
return
Scaffold(

body: _children[_currentIndex],

bottomNavigationBar: SizedBox(
child: BottomNavigationBar(
selectedFontSize: 0,
showSelectedLabels: false,
showUnselectedLabels: false,
type: BottomNavigationBarType.fixed,
items: [
BottomNavigationBarItem(
icon: _buildIcon(Icons.phone, 'Contacts', 0),
title: SizedBox.shrink(),
),
BottomNavigationBarItem(
title: SizedBox.fromSize(),
icon: _buildIcon(Icons.notifications_active, 'Notifications', 1)),
BottomNavigationBarItem(
icon: _buildIcon(Icons.more_horiz, 'More', 2),
return Scaffold(
body: _children[_currentIndex],
floatingActionButton: FloatingActionButton(
onPressed: () {
Navigator.of(context).pushNamed(ChatScreen.routeName);
},
child: const Icon(Icons.chat_bubble),
backgroundColor: Colors.indigo[700],
),
bottomNavigationBar: SizedBox(
child: BottomNavigationBar(
selectedFontSize: 0,
showSelectedLabels: false,
showUnselectedLabels: false,
type: BottomNavigationBarType.fixed,
items: [
BottomNavigationBarItem(
icon: _buildIcon(Icons.phone, 'Contacts', 0),
title: SizedBox.shrink(),
),
BottomNavigationBarItem(
title: SizedBox.fromSize(),
)
],
currentIndex: _currentIndex,
onTap: onTabTapped,
),

icon:
_buildIcon(Icons.notifications_active, 'Notifications', 1)),
BottomNavigationBarItem(
icon: _buildIcon(Icons.more_horiz, 'More', 2),
title: SizedBox.fromSize(),
)
],
currentIndex: _currentIndex,
onTap: onTabTapped,
),
);

),
);
}
}
}
7 changes: 5 additions & 2 deletions lib/generate_route.dart
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import 'package:campusbuddy/post_screen/posts.dart';
import 'package:campusbuddy/screens/department_list.dart';
import 'post_screen/events.dart';
import 'package:flutter/material.dart';

import 'package:campusbuddy/directory/chat_screen.dart';
class RouteGenerator {
static Route<dynamic> generateRoute(RouteSettings settings) {
switch (settings.name) {
Expand Down Expand Up @@ -47,7 +47,10 @@ class RouteGenerator {
final Deets deets = settings.arguments;
return MaterialPageRoute(
builder: (_) => Posts(deets));
default:
case ChatScreen.routeName:
return MaterialPageRoute(
builder: (_) => ChatScreen());
default:
return MaterialPageRoute(builder: (_) => Blank());
}
}
Expand Down