Advertisement
momo350

Chat app main tabs

Nov 6th, 2018
594
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Dart 24.77 KB | None | 0 0
  1. import 'package:flutter/material.dart';
  2. import 'package:scoped_model/scoped_model.dart';
  3. import 'package:cached_network_image/cached_network_image.dart';
  4. import 'package:material_search/material_search.dart';
  5. import '.././custom_widget/profile_card_widget.dart';
  6. import 'package:firebase_storage/firebase_storage.dart';
  7. import 'package:cloud_firestore/cloud_firestore.dart';
  8. import 'dart:async';
  9. import '.././ui/chat_screen_2.dart';
  10.  
  11. import '.././model/scoped_model.dart';
  12.  
  13. class GroupsScreen extends StatefulWidget {
  14.   @override
  15.   _ChatScreenState createState() => _ChatScreenState();
  16. }
  17.  
  18. class _ChatScreenState extends State<GroupsScreen>
  19.     with AutomaticKeepAliveClientMixin<GroupsScreen> {
  20.   @override
  21.   bool get wantKeepAlive => true;
  22.  
  23.   final _scaffoldKey = new GlobalKey<ScaffoldState>();
  24.   bool showBottomSheet = false;
  25.   bool hasEmail = false;
  26.   GlobalKey<FormState> _friendFormKey = GlobalKey();
  27.   String searchFriend;
  28.   bool emailExist = false;
  29.  
  30. //  Future<DocumentSnapshot> doesEmailExist() async {
  31. //    var snapshot = await Firestore.instance
  32. //        .collection('users')
  33. //        .document('$searchFriend')
  34. //        .get();
  35. //    if (snapshot.exists) {
  36. //      setState(() {
  37. //        emailExist = true;
  38. //      });
  39. //      print("Email existes");
  40. //    } else {
  41. //      setState(() {
  42. //        emailExist = false;
  43. //      });
  44. //      print("Email NOT existes");
  45. //    }
  46. //    return snapshot;
  47. //  }
  48.  
  49.   void _persistentBottomSheet() {
  50.     _scaffoldKey.currentState.showBottomSheet((context) {
  51.       return new Container(
  52.         color: Colors.white,
  53.         height: 250.0,
  54.         child: new Center(
  55.             child: Container(
  56.                 padding: EdgeInsets.all(10.0),
  57.                 child: Column(
  58.                   children: <Widget>[
  59.                     TextField(
  60.                       decoration: InputDecoration(labelText: 'Add Friend'),
  61.                     ),
  62.                     Padding(padding: EdgeInsets.only(top: 5.0)),
  63.                     FlatButton(
  64.                       shape: OutlineInputBorder(
  65.                           borderRadius: BorderRadius.circular(20.0)),
  66.                       color: Colors.blue,
  67.                       onPressed: () {},
  68.                       child: Text(
  69.                         "Add",
  70.                         style: TextStyle(color: Colors.white),
  71.                       ),
  72.                     ),
  73.                   ],
  74.                 ))),
  75.       );
  76.     });
  77.   }
  78.  
  79.   void _modalBottomSheet() {
  80.     showModalBottomSheet(
  81.         context: context,
  82.         builder: (builder) {
  83.           return new Container(
  84.             color: Colors.yellowAccent,
  85.             child: new Center(
  86.               child: new Text("Hey guys !! it is a modal bottom sheet"),
  87.             ),
  88.           );
  89.         });
  90.   }
  91.  
  92.   @override
  93.   Widget build(BuildContext context) {
  94. //    super.build(context);
  95.     return ScopedModelDescendant<MainModel>(
  96.       builder: (BuildContext context, Widget child, MainModel model) {
  97.         final double deviceWidth = MediaQuery
  98.             .of(context)
  99.             .size
  100.             .width;
  101.         final double deviceHeight = MediaQuery
  102.             .of(context)
  103.             .size
  104.             .height;
  105.         return DefaultTabController(
  106.           length: 3,
  107.           child: Scaffold(
  108.             key: _scaffoldKey,
  109. //            floatingActionButton: FloatingActionButton(
  110. //                child: Icon(Icons.add),
  111. //                onPressed: () {
  112. //                  setState(() {
  113. //                    showBottomSheet == true
  114. //                        ? showBottomSheet = false
  115. //                        : showBottomSheet = true;
  116. //                  });
  117. //                  if (showBottomSheet) {
  118. //                    _persistentBottomSheet();
  119. //                  } else {
  120. //                    Navigator.pop(context);
  121. //                    showBottomSheet = false;
  122. //                  }
  123. //                }),
  124.             appBar: AppBar(
  125.               backgroundColor: Colors.amber,
  126.               centerTitle: true,
  127.               title: Text("Momo Chat"),
  128.               actions: <Widget>[
  129.                 IconButton(
  130.                   icon: Icon(Icons.add),
  131.                   onPressed: () {
  132.                     _scaffoldKey.currentState.openEndDrawer();
  133.                   },
  134.                 ),
  135.               ],
  136.               bottom: TabBar(tabs: [
  137.                 Tab(icon: Icon(Icons.message)),
  138.                 Tab(icon: Icon(Icons.person)),
  139.                 Tab(icon: Icon(Icons.speaker_notes)),
  140.               ]),
  141.             ),
  142.             drawer: Drawer(
  143.               child: ListView(
  144.                 children: <Widget>[
  145.                   UserAccountsDrawerHeader(
  146.                     decoration: BoxDecoration(color: Colors.amber),
  147.                     accountName: Text(model.getUserModel.displayName),
  148.                     accountEmail: Text(model.getUserModel.email),
  149.                     currentAccountPicture: CircleAvatar(
  150.                       backgroundImage: CachedNetworkImageProvider(
  151.                           model.getUserModel.photoUrl),
  152.                     ),
  153.                   ),
  154.                   ListTile(
  155.                     trailing: Icon(Icons.person),
  156.                     title: Text("Account Info"),
  157.                     onTap: () => Navigator.pushNamed(context, '/accountInfo2'),
  158.                   ),
  159.                   ListTile(
  160.                     title: Text("Sign out"),
  161.                     trailing: Icon(Icons.exit_to_app),
  162.                     onTap: () {
  163.                       model.signOut().then((_) {
  164.                         Navigator.pushReplacementNamed(
  165.                             context, '/signInScreen');
  166.                       });
  167.                     },
  168.                   )
  169.                 ],
  170.               ),
  171.             ),
  172.             // ******* SEND DRAWER *******
  173.             endDrawer: Drawer(
  174.               child: ListView(
  175.                 children: <Widget>[
  176.                   Container(
  177.                     width: 50.0,
  178.                     color: Colors.amber,
  179.                     padding: EdgeInsets.all(20.0),
  180.                     child: Center(
  181.                       child: Text(
  182.                         "Add Some Friends",
  183.                         style: TextStyle(
  184.                             fontWeight: FontWeight.bold,
  185.                             fontSize: 18.0,
  186.                             color: Colors.white),
  187.                       ),
  188.                     ),
  189.                   ),
  190.                   // ****** ADD FRIEND ACCOUNT INFO ******
  191.                   hasEmail
  192.                       ? model.getDoesEmailExistBool
  193.                       ? FutureBuilder(
  194.                       future: model.getDoesEmailExist(),
  195.                       builder: (context, snapshot) {
  196. //                                if(snapshot.connectionState == ConnectionState.waiting){
  197. //                                  return Center(
  198. //                                    child: Text("Loading..."),
  199. //                                  );
  200. //                                }
  201. //                                return snapshot.hasData
  202. //                                    ? ProfileCard(
  203. //                                        name: snapshot.data['displayName']
  204. //                                            .toString(),
  205. //                                        email:
  206. //                                            snapshot.data['email'].toString(),
  207. //                                        bio: snapshot.data['bio'].toString(),
  208. //                                        photoUrl: snapshot.data['photoUrl']
  209. //                                            .toString())
  210. //                                    : Center(
  211. //                                        child: Container(
  212. //                                          padding: EdgeInsets.all(20.0),
  213. //                                          child: CircularProgressIndicator(),
  214. //                                        ),
  215. //                                      );
  216.  
  217.                         switch (snapshot.connectionState) {
  218.                           case ConnectionState.waiting:
  219.                             return Center(
  220.                               child: Text("Loading..."),
  221.                             );
  222.                           case ConnectionState.done:
  223.                             return ProfileCard(
  224.                                 name: snapshot.data['displayName']
  225.                                     .toString(),
  226.                                 email:
  227.                                 snapshot.data['email'].toString(),
  228.                                 bio: snapshot.data['bio'].toString(),
  229.                                 photoUrl: snapshot.data['photoUrl']
  230.                                     .toString());
  231.  
  232.                           default:
  233.                             return Text("No User Found");
  234.                         }
  235.                       })
  236.                       : Center(
  237.                     child: Container(
  238.                       padding: EdgeInsets.all(20.0),
  239.                       child: Text("No Email exist"),
  240.                     ),
  241.                   )
  242.                       : Container(),
  243.  
  244.                   hasEmail == false
  245.                       ? Container(
  246.                     padding: EdgeInsets.all(10.0),
  247.                     child: Form(
  248.                       key: _friendFormKey,
  249.                       child: TextFormField(
  250.                         onSaved: (value) {
  251.                           setState(() {
  252.                             searchFriend = value;
  253.                           });
  254.                           model.doesEmailExist(searchFriend);
  255.                         },
  256.                         decoration: InputDecoration(
  257.                             hintText: "enter email",
  258.                             border: OutlineInputBorder(
  259.                               borderRadius: BorderRadius.circular(20.0),
  260.                             )),
  261.                       ),
  262.                     ),
  263.                   )
  264.                       : Container(),
  265.                   hasEmail
  266.                       ? Column(
  267.                     children: <Widget>[
  268.                       model.getDoesEmailExistBool
  269.                           ? Container(
  270.                         width: double.infinity,
  271.                         padding: EdgeInsets.all(10.0),
  272.                         child: FlatButton(
  273.                           shape: OutlineInputBorder(
  274.                               borderRadius:
  275.                               BorderRadius.circular(20.0)),
  276.                           color: Colors.blue,
  277.                           onPressed: () {
  278.                             model.addFriend();
  279.                             setState(() {
  280.                               hasEmail
  281.                                   ? hasEmail = false
  282.                                   : hasEmail = true;
  283.                             });
  284.                           },
  285.                           child: Text(
  286.                             'Add!',
  287.                             style: TextStyle(
  288.                               color: Colors.white,
  289.                             ),
  290.                           ),
  291.                         ),
  292.                       )
  293.                           : Container(),
  294.                       Container(
  295.                         width: double.infinity,
  296.                         padding: EdgeInsets.all(10.0),
  297.                         child: FlatButton(
  298.                           shape: OutlineInputBorder(
  299.                               borderRadius: BorderRadius.circular(20.0)),
  300.                           color: Colors.blue,
  301.                           onPressed: () {
  302.                             setState(() {
  303.                               emailExist = false;
  304.                               hasEmail = false;
  305.                             });
  306.                           },
  307.                           child: Text(
  308.                             'Search another',
  309.                             style: TextStyle(
  310.                               color: Colors.white,
  311.                             ),
  312.                           ),
  313.                         ),
  314.                       ),
  315.                     ],
  316.                   )
  317.                       : Container(
  318.                     padding: EdgeInsets.all(10.0),
  319.                     child: FlatButton(
  320.                       shape: OutlineInputBorder(
  321.                           borderRadius: BorderRadius.circular(20.0)),
  322.                       color: Colors.blue,
  323.                       onPressed: () {
  324.                         _friendFormKey.currentState.save();
  325.                         model.setDoesEmailExistFalse(false);
  326.                         setState(() {
  327.                           hasEmail ? hasEmail = false : hasEmail = true;
  328.                         });
  329.                       },
  330.                       child: Text(
  331.                         'Search!',
  332.                         style: TextStyle(
  333.                           color: Colors.white,
  334.                         ),
  335.                       ),
  336.                     ),
  337.                   ),
  338.                 ],
  339.               ),
  340.             ),
  341.             body: TabBarView(children: [
  342.               // ****** CHATS ********
  343.  
  344.  
  345.               StreamBuilder<QuerySnapshot>(
  346.                 stream: Firestore.instance
  347.                     .collection('user friends list')
  348.                     .document(model.getUserModel.email)
  349.                     .collection('friends')
  350.                     .orderBy('email', descending: true)
  351.                     .limit(20)
  352.                     .snapshots(),
  353.                 builder: (BuildContext context,
  354.                     AsyncSnapshot<QuerySnapshot> snapshot) {
  355.                   if (!snapshot.hasData) return Container();
  356.                   return ListView.builder(
  357.                     itemCount: snapshot.data.documents.length,
  358.                     itemBuilder: (BuildContext context, int index) {
  359.                       String friendEmail = snapshot
  360.                           .data.documents[index].data['email']
  361.                           .toString();
  362.  
  363.                       String groupChatId;
  364.                       readLocal() {
  365.                         if (model.getUserModel.email.hashCode <=
  366.                             friendEmail.hashCode) {
  367.                           groupChatId =
  368.                           '$friendEmail and ${model.getUserModel.email}';
  369.                           print(" GROUP CHAT ID $groupChatId");
  370.                         } else {
  371.                           groupChatId =
  372.                           '${model.getUserModel.email} and $friendEmail';
  373.                           print(" GROUP CHAT ID $groupChatId");
  374.                         }
  375.                       }
  376.  
  377.                       readLocal();
  378.  
  379.                       return GestureDetector(
  380.                         onTap: () {
  381.                             model.currentChat('$friendEmail');
  382.                           Navigator.pushNamed(context, '/chatScreen');
  383.                         },
  384.                         child: Container(
  385.                           color: Colors.transparent,
  386.                             width: double.infinity,
  387.                           child: Row(
  388.                             children: <Widget>[
  389.  
  390.                               Container(
  391.                                 padding: EdgeInsets.all(10.0),
  392.                                 child: getFriendPhoto(friendEmail, deviceWidth),
  393.                               ),
  394.                               Flexible(
  395.                                 child: Container(
  396.                                   padding: EdgeInsets.all(10.0),
  397.                                   child: Column(
  398.                                     crossAxisAlignment:
  399.                                     CrossAxisAlignment.start,
  400.                                     children: <Widget>[
  401.                                       Container(
  402.                                         padding: EdgeInsets.only(
  403.                                             top: 5.0, bottom: 2.0),
  404.                                         child: getFriendDisplayName(
  405.                                             friendEmail),
  406.                                       ),
  407.                                       Container(
  408.                                           padding: EdgeInsets.only(bottom: 5.0),
  409.                                           child: getLatestMessage(groupChatId),
  410.  
  411.                                       ),
  412.                                     ],
  413.                                   ),
  414.                                 ),
  415.                               ),
  416.                             ],
  417.                           ),
  418.                         ),
  419.                       );
  420.                     },
  421.                   );
  422.                 },
  423.               ),
  424.  
  425.               // ****** FRIEND LIST ******
  426.               StreamBuilder<QuerySnapshot>(
  427.                 stream: Firestore.instance
  428.                     .collection('user friends list')
  429.                     .document(model.getUserModel.email)
  430.                     .collection('friends')
  431.                     .orderBy('email', descending: true)
  432.                     .limit(20)
  433.                     .snapshots(),
  434.                 builder: (BuildContext context,
  435.                     AsyncSnapshot<QuerySnapshot> snapshot) {
  436.                   if (!snapshot.hasData) return Container();
  437.                   return ListView.builder(
  438.                     itemCount: snapshot.data.documents.length,
  439.                     itemBuilder: (BuildContext context, int index) {
  440.                       String friendEmail = snapshot
  441.                           .data.documents[index].data['email']
  442.                           .toString();
  443.                       return StreamBuilder(
  444.                         stream: Firestore.instance
  445.                             .collection('users')
  446.                             .document(friendEmail)
  447.                             .snapshots(),
  448.                         builder: (context, snapshot) {
  449.                           switch (snapshot.connectionState) {
  450.                             case ConnectionState.none:
  451.                               return Text("none");
  452.                             case ConnectionState.waiting:
  453.                               return Container();
  454.                             default:
  455.                               if (snapshot.hasData) {
  456.                                 return friendInfoListTile(
  457.                                     snapshot, model, deviceHeight);
  458.                               } else {
  459.                                 return Text("No data");
  460.                               }
  461.                           }
  462.                         },
  463.                       );
  464.                     },
  465.                   );
  466.                 },
  467.               ),
  468.               Center(
  469.                   child: Text("This Function Is Coming Soon!"),
  470.                   ),
  471.             ]),
  472.           ),
  473.         );
  474.       },
  475.     );
  476.   }
  477.  
  478.   Widget friendInfoListTile(snapshot, model, deviceHeight) {
  479.     return GestureDetector(
  480.       onTap: () {
  481.         setState(() {
  482.           model.currentChat('${snapshot.data['email']}');
  483.         });
  484.         Navigator.pushNamed(context, '/chatScreen');
  485.       },
  486.       child: Container(
  487.         color: Colors.transparent,
  488.         width: double.infinity,
  489.         padding: EdgeInsets.symmetric(horizontal: 5.0),
  490.         child: Row(
  491.           children: <Widget>[
  492.             Container(
  493.               padding: EdgeInsets.all(5.0),
  494.               child: CircleAvatar(
  495.                 radius: deviceHeight / 32,
  496.                 backgroundImage:
  497.                 CachedNetworkImageProvider('${snapshot.data['photoUrl']}'),
  498.               ),
  499.             ),
  500.             Flexible(
  501.               child: Container(
  502.                 padding: EdgeInsets.all(10.0),
  503.                 child: Column(
  504.                   crossAxisAlignment: CrossAxisAlignment.start,
  505.                   children: <Widget>[
  506.                     Container(
  507.                         padding: EdgeInsets.only(top: 5.0, bottom: 2.0),
  508.                         child: Text(
  509.                           '${snapshot.data['displayName']}',
  510.                           style: TextStyle(
  511. //                            fontWeight: FontWeight.bold,
  512.                               fontSize: 17.0),
  513.                           overflow: TextOverflow.ellipsis,
  514.                         )),
  515.                     Container(
  516.                       padding: EdgeInsets.only(bottom: 5.0),
  517.                       child: Text('${snapshot.data['email']}'),
  518.                     ),
  519.                   ],
  520.                 ),
  521.               ),
  522.             )
  523.           ],
  524.         ),
  525.       ),
  526.     );
  527.   }
  528.  
  529.   Widget getLatestMessage(groupChatId) {
  530.     return StreamBuilder(
  531.       stream: Firestore.instance
  532.           .collection('messages')
  533.           .document(groupChatId)
  534.           .collection(groupChatId)
  535.           .orderBy('sentOn', descending: true)
  536.           .limit(1)
  537.           .snapshots(),
  538.       builder: (context, snapshot) {
  539.         try {
  540.           if (snapshot.data.documents[0] == null) {
  541.             return Text("No Data");
  542.           } else {
  543.             if (snapshot.data.documents[0].data['type'] == '0') {
  544.               String message = snapshot.data.documents[0].data['message']
  545.                   .replaceAll("\n", " ");
  546.               return Text(
  547.                 message.toString(),
  548.                 overflow: TextOverflow.ellipsis,
  549.                 style: TextStyle(
  550.                   fontSize: 15.0
  551.                 ),
  552.               );
  553.             } else {
  554.               return Text("Image");
  555.             }
  556.           }
  557.         } catch (e) {
  558.           if (snapshot.connectionState == ConnectionState.waiting) {
  559.             return Text(" ");
  560.           }
  561.           return Text("No Message Yet!");
  562.         }
  563.       },
  564.     );
  565.   }
  566.  
  567.   Widget getFriendDisplayName(friendEmail) {
  568.     return StreamBuilder(
  569.       stream: Firestore.instance
  570.           .collection('users')
  571.           .document(friendEmail)
  572.           .snapshots(),
  573.       builder: (context, snapshot) {
  574.         switch (snapshot.connectionState) {
  575.           case ConnectionState.none:
  576.             return Text("none");
  577.           case ConnectionState.waiting:
  578.             return Container();
  579.           default:
  580.             if (snapshot.hasData) {
  581.               return Text("${snapshot.data['displayName']}", style: TextStyle(fontSize: 18.0),);
  582.             } else {
  583.               return Text("No data");
  584.             }
  585.         }
  586.       },
  587.     );
  588.   }
  589.  
  590.   Widget getFriendPhoto(friendEmail, deviceWidth) {
  591.     return StreamBuilder(
  592.       stream: Firestore.instance
  593.           .collection('users')
  594.           .document(friendEmail)
  595.           .snapshots(),
  596.       builder: (context, snapshot) {
  597.         switch (snapshot.connectionState) {
  598.           case ConnectionState.none:
  599.             return Text("none");
  600.           case ConnectionState.waiting:
  601.             return Container();
  602.           default:
  603.             if (snapshot.hasData) {
  604.               return CircleAvatar(
  605.                 radius: deviceWidth / 15,
  606.                 backgroundImage:
  607.                 CachedNetworkImageProvider(snapshot.data['photoUrl']),
  608.               );
  609.             } else {
  610.               return Text("No data");
  611.             }
  612.         }
  613.       },
  614.     );
  615.   }
  616.  
  617.   Future<Map<String, String>> future(friendEmail) async {
  618.     DocumentSnapshot snapshot = await Firestore.instance
  619.         .collection('users')
  620.         .document('$friendEmail')
  621.         .get();
  622.     String email = snapshot.data['email'];
  623.     String displayName = snapshot.data['displayName'];
  624.     String photoUrl = snapshot.data['photoUrl'];
  625.  
  626.     Map<String, String> friendData = {
  627.       'email': email,
  628.       'displayName': displayName,
  629.       'photoUrl': photoUrl,
  630.     };
  631.     return friendData;
  632.   }
  633.  
  634.   Widget userListTileBasic(friendEmail) {
  635.     return ListTile(
  636.       title: Text('$friendEmail'),
  637.     );
  638.   }
  639. }
  640.  
  641. class friendProfilePic extends StatefulWidget {
  642.   String friendEmail;
  643.  
  644.   friendProfilePic(this.friendEmail);
  645.  
  646.   @override
  647.   _friendProfilePicState createState() => _friendProfilePicState();
  648. }
  649.  
  650. class _friendProfilePicState extends State<friendProfilePic> {
  651.   @override
  652.   Widget build(BuildContext context) {
  653.     return StreamBuilder(
  654.       stream: Firestore.instance
  655.           .collection('users')
  656.           .document(widget.friendEmail)
  657.           .snapshots(),
  658.       builder: (context, snapshot) {
  659.         switch (snapshot.connectionState) {
  660.           case ConnectionState.none:
  661.             return Text("none");
  662.           case ConnectionState.waiting:
  663.             return Container();
  664.           default:
  665.             if (snapshot.hasData) {
  666.               return CircleAvatar(
  667.                 backgroundImage:
  668.                 CachedNetworkImageProvider(snapshot.data['photoUrl']),
  669.               );
  670.             } else {
  671.               return Text("No data");
  672.             }
  673.         }
  674.       },
  675.     );
  676.   }
  677. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement