Advertisement
Guest User

Untitled

a guest
Jan 12th, 2019
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Dart 20.37 KB | None | 0 0
  1. //Chat screen which lists all the chat messages, including _handleSubmitted and the _buildTextComposer
  2.  
  3. import 'dart:math';
  4. import 'dart:io';
  5.  
  6. import 'package:flutter/cupertino.dart';
  7. import 'package:flutter/foundation.dart';
  8. import 'package:flutter/material.dart';
  9. import 'package:image_picker/image_picker.dart';
  10. import 'package:firebase_storage/firebase_storage.dart';
  11. import 'package:cloud_firestore/cloud_firestore.dart';
  12. import 'package:firebase_database/firebase_database.dart';
  13. import 'package:intl/intl.dart';
  14. import 'package:fluttertoast/fluttertoast.dart';
  15. import 'package:cached_network_image/cached_network_image.dart';
  16. import 'package:transparent_image/transparent_image.dart';
  17. import 'package:flutter_image/network.dart';
  18. import 'package:flutter_native_image/flutter_native_image.dart';
  19. import 'package:photo_view/photo_view.dart';
  20. import 'package:first_app/image_large.dart';
  21. import 'package:incrementally_loading_listview/incrementally_loading_listview.dart';
  22.  
  23. final database = Firestore.instance
  24.     .collection('nachrichten')
  25.     .document('G5xlQHvb56ZqpWs7ojUV');
  26. final reference = FirebaseDatabase.instance.reference().child('messages');
  27.  
  28. class ChatScreen extends StatefulWidget {
  29.   @override
  30.   State createState() => new ChatScreenState();
  31. }
  32.  
  33. class ChatScreenState extends State<ChatScreen> with TickerProviderStateMixin {
  34.   final TextEditingController _textController = new TextEditingController();
  35.   final ScrollController _scrollController = new ScrollController();
  36.  
  37.   bool _isComposing = false;
  38.   bool isLoading;
  39.   String imageUrl;
  40.   File imageFile;
  41.  
  42.   //optional from other code
  43.   @override
  44.   void initState() {
  45.     super.initState();
  46.     imageUrl = '';
  47.   }
  48.  
  49.   Future getImage() async {
  50.     imageFile = await ImagePicker.pickImage(source: ImageSource.camera);
  51.  
  52.     if (imageFile != null) {
  53.       setState(() {
  54.         isLoading = true;
  55.       });
  56.       uploadFile();
  57.     }
  58.   }
  59.  
  60.   Future uploadFile() async {
  61.     //file compression
  62.     File compressedFile = await FlutterNativeImage.compressImage(imageFile.path,
  63.         quality: 50, percentage: 50);
  64.     String fileName = DateTime.now().millisecondsSinceEpoch.toString();
  65.     StorageReference reference = FirebaseStorage.instance.ref().child(fileName);
  66.     StorageUploadTask uploadTask = reference.putFile(compressedFile);
  67.     StorageTaskSnapshot storageTaskSnapshot = await uploadTask.onComplete;
  68.     storageTaskSnapshot.ref.getDownloadURL().then((downloadUrl) {
  69.       imageUrl = downloadUrl;
  70.       setState(() {
  71.         isLoading = false;
  72.         _handleSubmitted(imageUrl: imageUrl);
  73.       });
  74.     }, onError: (err) {
  75.       setState(() {
  76.         isLoading = false;
  77.       });
  78.       Fluttertoast.showToast(msg: 'This file is not an image');
  79.     });
  80.   }
  81.  
  82.   //Builds the button text composer, including camera icon, text input and send button
  83.   Widget _buildTextComposer() {
  84.     return new IconTheme(
  85.       data: new IconThemeData(color: Theme.of(context).accentColor),
  86.       child: new Container(
  87.           margin: const EdgeInsets.symmetric(horizontal: 0.80),
  88.           child: new Row(children: <Widget>[
  89.             new Container(
  90.               margin: new EdgeInsets.symmetric(horizontal: 0.4),
  91.               child: new IconButton(
  92.                 icon: new Icon(Icons.photo_camera),
  93.                 onPressed: getImage,
  94.                 /*() async {
  95.                     File imageFile =
  96.                         await ImagePicker.pickImage(source: ImageSource.camera);
  97.                     int random = new Random().nextInt(100000);
  98.  
  99.                     //compression of picked image via native image compression library, choose values for quality and percentage between 1-100
  100. //                    File compressedFile = await FlutterNativeImage.compressImage(imageFile.path,
  101. //                        quality: 100, percentage: 100);
  102.  
  103.                     StorageReference ref = FirebaseStorage.instance
  104.                         .ref()
  105.                         .child("image_$random.jpg");
  106.                     StorageUploadTask uploadTask = ref.putFile(compressedFile);
  107.                     StorageTaskSnapshot storageTaskSnapshot =
  108.                         await uploadTask.onComplete;
  109.  
  110.                     storageTaskSnapshot.ref.getDownloadURL().then((downloadUrl) {
  111.                       imageUrl = downloadUrl;
  112.  
  113.                       setState(() {
  114.                         isLoading = false;
  115.                         _handleSubmitted(imageUrl: imageUrl);
  116.                       });
  117.                     });
  118.  
  119. //                    String downloadUrl =
  120. //                        await storageTaskSnapshot.ref.getDownloadURL();
  121. //                                      _handleSubmitted(downloadUrl: downloadUrl);
  122.  
  123. */ /*                    _sendMessage(imageUrl: downloadUrl.toString());*/ /*
  124.                   }*/
  125.               ),
  126.             ),
  127.             new Flexible(
  128.               child: Container(
  129.                 margin: const EdgeInsets.symmetric(vertical: 10.0),
  130.                 padding: EdgeInsets.all(10.0),
  131.                 decoration: new BoxDecoration(
  132.                   border: Border.all(color: Colors.grey.shade200),
  133.                   borderRadius: new BorderRadius.circular(20.0),
  134.                 ),
  135.  
  136.                 //container with constraint limits the maximum height of the text input field
  137.                 child: new Container(
  138.                   constraints: BoxConstraints.loose(Size.fromHeight(100.0)),
  139.                   child: new TextField(
  140.                     maxLines: null,
  141.                     keyboardType: TextInputType.multiline,
  142.                     controller: _textController,
  143.                     onChanged: (String text) {
  144.                       setState(() {
  145.                         _isComposing = text.length > 0;
  146.                       });
  147.                     },
  148. //                    onSubmitted: _handleSubmitted,
  149.                     decoration: new InputDecoration.collapsed(
  150.                         hintText: "Nachricht schreiben..."),
  151.                   ),
  152.                 ),
  153.               ),
  154.             ),
  155.             new Container(
  156.                 margin: new EdgeInsets.symmetric(horizontal: 0.4),
  157.                 child: Theme.of(context).platform == TargetPlatform.iOS
  158.                     ? new CupertinoButton(
  159.                         child: new Text("Send"),
  160.                         onPressed: _isComposing
  161.                             ? () => _handleSubmitted(text: _textController.text)
  162.                             : null,
  163.                       )
  164.                     : new IconButton(
  165.                         icon: new Icon(Icons.send),
  166.                         onPressed: _isComposing
  167.                             ? () => _handleSubmitted(text: _textController.text)
  168.                             : null,
  169.                       )),
  170.           ]),
  171.           decoration: Theme.of(context).platform == TargetPlatform.iOS
  172.               ? new BoxDecoration(
  173.                   border:
  174.                       new Border(top: new BorderSide(color: Colors.grey[200])))
  175.               : null),
  176.     );
  177.   }
  178.  
  179.   //Builds the actual chat screen with Scaffold
  180.   Widget build(BuildContext context) {
  181.     return new Scaffold(
  182.       appBar: new AppBar(
  183.           title: new Text("Chat.here Gruppenchat"),
  184.           centerTitle: true,
  185.           elevation:
  186.               Theme.of(context).platform == TargetPlatform.iOS ? 0.0 : 4.0),
  187.       body: StreamBuilder<QuerySnapshot>(
  188.           stream: Firestore.instance
  189.               .collection('nachrichten')
  190.               .orderBy('timestamp', descending: true)
  191.               //  .limit(20)
  192.               .snapshots(),
  193.           builder:
  194.               (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
  195.             if (!snapshot.hasData) return Text('Loading data');
  196.             final int documentsLength = snapshot.data.documents.length;
  197.             return Container(
  198.                 child: Column(
  199.                   children: <Widget>[
  200.                     new Flexible(
  201.                         child: ListView.builder(
  202.                       controller: _scrollController,
  203.                       reverse: true,
  204.                       itemCount: documentsLength,
  205.  
  206.                       /*ALTERNATIVE INFINITE LISTVIEW
  207.                         IncrementallyLoadingListView(
  208.                           itemCount: () => documentsLength,
  209.                           loadMoreOffsetFromBottom: 2,*/
  210.  
  211.                       itemBuilder: (context, int index) {
  212.                         final DocumentSnapshot document =
  213.                             snapshot.data.documents[index];
  214.                         return new Container(
  215.                           margin: const EdgeInsets.symmetric(
  216.                               horizontal: 10.0, vertical: 10.0),
  217.                           child: new Row(
  218.                             crossAxisAlignment: CrossAxisAlignment.start,
  219.                             children: <Widget>[
  220.                               new Container(
  221.                                 margin: const EdgeInsets.only(right: 16.0),
  222.                                 child: new CircleAvatar(
  223.                                     child: new Text(
  224.                                         document['author'].substring(0, 1))),
  225.                               ),
  226.                               new Expanded(
  227.                                 child: new Column(
  228.                                   crossAxisAlignment: CrossAxisAlignment.start,
  229.                                   children: <Widget>[
  230.                                     new Row(
  231.                                       children: <Widget>[
  232.                                         new Text(document['author'],
  233.                                             style: TextStyle(
  234.                                                 fontSize: 12.0,
  235.                                                 color: Colors.black45,
  236.                                                 fontWeight: FontWeight.bold)),
  237.                                         new Text(
  238.                                             ' ' +
  239.                                                 DateFormat("MMM. d. '|' HH:mm")
  240.                                                     .format(
  241.                                                         document['timestamp']),
  242.                                             style: TextStyle(
  243.                                                 fontSize: 12.0,
  244.                                                 color: Colors.black45))
  245.                                       ],
  246.                                     ),
  247.  
  248.                             //        Container (child: Image.asset('images/placeholder.jpg')),
  249.  
  250.                                     //can be deleted. just to test the picture.
  251.                                     (document['text'] == null)
  252.                                         ? new GestureDetector(
  253.                                             onTap: () {
  254.                                               Navigator.push(
  255.                                                 context,
  256.                                                 MaterialPageRoute(
  257.                                                     builder: (context) =>
  258.                                                         SecondScreen(
  259.                                                             imageUrl: document[
  260.                                                                 'imageUrl'])),
  261.                                               );
  262.                                             },
  263.                                             child: new Container(
  264.                                               child: new ClipRRect(
  265.                                                 borderRadius:
  266.                                                     new BorderRadius.circular(
  267.                                                         7.0),
  268.                                                 child: new CachedNetworkImage(
  269.                                                   imageUrl:
  270.                                                       document['imageUrl'],
  271.                                                   placeholder: Container(
  272.                                                     child:
  273.                                                         CircularProgressIndicator(
  274.                                                       valueColor:
  275.                                                           AlwaysStoppedAnimation<
  276.                                                                   Color>(
  277.                                                               Colors.orange),
  278.                                                     ),
  279.                                                     width: 200.0,
  280.                                                     height: 200.0,
  281.                                                     padding:
  282.                                                         EdgeInsets.all(70.0),
  283.                                                     decoration: BoxDecoration(
  284.                                                       borderRadius:
  285.                                                           BorderRadius.all(
  286.                                                         Radius.circular(8.0),
  287.                                                       ),
  288.                                                     ),
  289.                                                   ),
  290.                                                 ),
  291.  
  292. //   ALTERNATIVE
  293. /*                                              CachedNetworkImage(
  294.                                                 placeholder: Container(
  295.                                                   child: CircularProgressIndicator(
  296.                                                     valueColor: AlwaysStoppedAnimation<Color>(Colors.orange),
  297.                                                   ),
  298.                                                   width: 200.0,
  299.                                                   height: 200.0,
  300.                                                   padding: EdgeInsets.all(70.0),
  301.                                                   decoration: BoxDecoration(
  302.                                                     color: Colors.blue,
  303.                                                     borderRadius: BorderRadius.all(
  304.                                                       Radius.circular(8.0),
  305.                                                     ),
  306.                                                   ),
  307.                                                 ),
  308.                                                 imageUrl: 'images/placeholder.jpg',
  309.                                                 width: 200.0,
  310.                                                 height: 200.0,
  311.                                                 fit: BoxFit.cover,
  312.                                               ),*/
  313.  
  314.                                                 /*Image.network(
  315.                                           'https://firebasestorage.googleapis.com/v0/b/chat-d1108.appspot.com/o/image_28089.jpg?alt=media&token=f0338b3e-ef7f-4460-b5cf-badaf1804e5a',
  316.                                           height: 300.0,
  317.                                           width: 200.0,
  318.                                           fit: BoxFit.fill),*/
  319.                                               ),
  320.                                               margin:
  321.                                                   EdgeInsets.only(right: 50.0),
  322.                                             ))
  323.  
  324. //                                    ALTERNATIVE
  325. //                                    new Container(
  326. //                                      child: new ClipRRect(
  327. //                                        borderRadius:
  328. //                                            new BorderRadius.circular(7.0),
  329. //                                        child: new Image(
  330. //                                          image: new NetworkImageWithRetry(
  331. //                                              document['imageUrl']),
  332. //                                        ),
  333. //                                      ),
  334. //                                      margin: EdgeInsets.only(right: 50.0),
  335. //                                    )
  336.  
  337.                                         : new Card(
  338.                                             margin:
  339.                                                 EdgeInsets.only(right: 50.0),
  340.                                             //green color for messages of yourself
  341.                                             color:
  342.                                                 document['author'] == "Matthias"
  343.                                                     ? Color.fromRGBO(
  344.                                                         220, 255, 202, 1.0)
  345.                                                     : null,
  346.                                             child: new Container(
  347.                                                 padding: EdgeInsets.all(6.0),
  348.                                                 child: new Text(
  349.                                                   document['text'],
  350.                                                   style:
  351.                                                       TextStyle(fontSize: 15.0),
  352.                                                 )),
  353.                                             shape: RoundedRectangleBorder(
  354.                                                 borderRadius:
  355.                                                     BorderRadius.circular(7.0)),
  356.                                           ),
  357.  
  358.                                     /*new Container(
  359.                       margin: const EdgeInsets.only(top: 5.0),
  360.                       child: snapshot.value['imageUrl'] != null
  361.                           ? new Image.network(
  362.                               snapshot.value['imageUrl'],
  363.                               width: 250.0,
  364.                             )
  365.                           : new Text(snapshot.value['text']),
  366.                     ),*/
  367.  
  368.                                     //Container( child: image != null ? new Image.file(image, width: 250.0) : new Text("Kein Bild"))
  369.                                   ],
  370.                                 ),
  371.                               ),
  372.                             ],
  373.                           ),
  374.                         );
  375.                       },
  376.                     )),
  377.                     new Divider(height: 1.0),
  378.                     new Container(
  379.                       decoration:
  380.                           new BoxDecoration(color: Theme.of(context).cardColor),
  381.                       child: _buildTextComposer(),
  382.                     ),
  383.                   ],
  384.                 ),
  385.                 decoration: Theme.of(context).platform == TargetPlatform.iOS
  386.                     ? new BoxDecoration(
  387.                         border: new Border(
  388.                             top: new BorderSide(color: Colors.grey[200])))
  389.                     : null);
  390.           }),
  391.     );
  392.   }
  393.  
  394. /*  void _handleSubmittedImage(String downloadUrl){
  395.     Firestore.instance.runTransaction((Transaction transaction) async {
  396.       CollectionReference reference =
  397.       Firestore.instance.collection('nachrichten');
  398.  
  399.       await reference.add({
  400.         "imageURL": downloadUrl,
  401.         "author": "Matthias",
  402.         "timestamp": DateTime.now(),
  403.  
  404.         //"timestamp": FieldValue.serverTimestamp()
  405.       });
  406.     });
  407.   }*/
  408.  
  409.   void _handleSubmitted({String text, String imageUrl}) {
  410.     _textController.clear();
  411.     setState(() {
  412.       _isComposing = false;
  413.     });
  414.  
  415.     //creation of an own document in Firestore
  416.     Firestore.instance.runTransaction((Transaction transaction) async {
  417.       CollectionReference reference =
  418.           Firestore.instance.collection('nachrichten');
  419.  
  420.       await reference.add({
  421.         "text": text,
  422.         "author": "Matthias",
  423.         "imageUrl": imageUrl,
  424.         "timestamp": DateTime.now(),
  425.  
  426.         //"timestamp": FieldValue.serverTimestamp()
  427.       });
  428.     });
  429.  
  430. /*    Firestore.instance
  431.         .collection('nachrichten')
  432.         .snapshots()
  433.         .listen((data) => data.documents.forEach((doc) {
  434.               List list = [];
  435.               list.add(doc["text"]);
  436.             }));*/
  437.  
  438. //Let the chat list jump to the newest chat message at the bottom
  439.     _scrollController.animateTo(
  440.       0.0,
  441.       curve: Curves.easeOut,
  442.       duration: const Duration(milliseconds: 300),
  443.     );
  444.   }
  445. /*  void _sendMessage({String text, String imageUrl}) {
  446.     reference.push().set({'text': text, 'imageUrl': imageUrl});
  447.   }*/
  448. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement