Guest User

Untitled

a guest
May 27th, 2018
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.68 KB | None | 0 0
  1. import 'dart:async';
  2. import 'dart:io';
  3. import 'dart:math';
  4.  
  5. import 'package:firebase_analytics/firebase_analytics.dart';
  6. import 'package:firebase_auth/firebase_auth.dart';
  7. import 'package:firebase_database/firebase_database.dart';
  8. import 'package:firebase_database/ui/firebase_animated_list.dart';
  9. import 'package:firebase_storage/firebase_storage.dart';
  10.  
  11. import 'package:flutter/cupertino.dart';
  12. import 'package:flutter/foundation.dart';
  13. import 'package:flutter/material.dart';
  14.  
  15. import 'package:google_sign_in/google_sign_in.dart';
  16. import 'package:image_picker/image_picker.dart';
  17.  
  18.  
  19. final auth = FirebaseAuth.instance;
  20. final analytics = new FirebaseAnalytics();
  21. final googleSignIn = new GoogleSignIn();
  22. final reference = FirebaseDatabase.instance.reference().child('messages');
  23.  
  24. void main() => runApp(new FriendlychatApp());
  25.  
  26. final ThemeData kIOSTheme = new ThemeData(
  27. primarySwatch: Colors.orange,
  28. primaryColor: Colors.grey[100],
  29. primaryColorBrightness: Brightness.light,
  30. );
  31.  
  32. final ThemeData kDefaultTheme = new ThemeData(
  33. primarySwatch: Colors.purple,
  34. accentColor: Colors.orangeAccent[400],
  35. );
  36.  
  37. class FriendlychatApp extends StatelessWidget {
  38. @override
  39. Widget build(BuildContext context) {
  40. return new MaterialApp(
  41. title: "Friendlychat",
  42. theme: defaultTargetPlatform == TargetPlatform.iOS
  43. ? kIOSTheme : kDefaultTheme,
  44. home: new ChatScreen(),
  45. );
  46. }
  47. }
  48.  
  49. class ChatMessage extends StatelessWidget {
  50. ChatMessage({this.snapshot, this.animation});
  51. final DataSnapshot snapshot;
  52. final Animation animation;
  53.  
  54. @override
  55. Widget build(BuildContext context) {
  56. return new FadeTransition(
  57. opacity: new CurvedAnimation(
  58. parent: animation, curve: Curves.easeOut
  59. ),
  60. child: new Container(
  61. margin: const EdgeInsets.symmetric(vertical: 10.0),
  62. child: new Row(
  63. crossAxisAlignment: CrossAxisAlignment.start,
  64. children: <Widget>[
  65. new Container(
  66. margin: const EdgeInsets.only(right: 16.0),
  67. child: new CircleAvatar(
  68. backgroundImage: new NetworkImage(snapshot.value['senderPhotoUrl']),
  69. ),
  70. ),
  71. new Expanded(
  72. child: new Column(
  73. crossAxisAlignment: CrossAxisAlignment.start,
  74. children: <Widget>[
  75. new Text(
  76. snapshot.value['senderName'],
  77. style: Theme.of(context).textTheme.subhead
  78. ),
  79. new Container(
  80. margin: const EdgeInsets.only(top: 5.0),
  81. child: snapshot.value['imageUrl'] != null ?
  82. new Image.network(
  83. snapshot.value['imageUrl'],
  84. width: 250.0,
  85. ) : new Text(snapshot.value['text']),
  86. ),
  87. ],
  88. ),
  89. ),
  90. ],
  91. ),
  92. ),
  93. );
  94. }
  95. }
  96.  
  97. class ChatScreen extends StatefulWidget {
  98. @override
  99. State createState() => new ChatScreenState();
  100. }
  101.  
  102. class ChatScreenState extends State<ChatScreen> {
  103. final TextEditingController _textController = new TextEditingController();
  104. bool _isComposing = false;
  105.  
  106. Future<Null> _ensureLoggedIn() async {
  107. GoogleSignInAccount user = googleSignIn.currentUser;
  108. if (user == null) {
  109. user = await googleSignIn.signInSilently();
  110. }
  111. if (user == null) {
  112. await googleSignIn.signIn();
  113. analytics.logLogin();
  114. }
  115. if (await auth.currentUser() == null) {
  116. GoogleSignInAuthentication credentials = await googleSignIn.currentUser.authentication;
  117. await auth.signInWithGoogle(
  118. idToken: credentials.idToken,
  119. accessToken: credentials.accessToken,
  120. );
  121. }
  122. }
  123.  
  124. void _handleSubmitted(String text) async {
  125. _textController.clear();
  126.  
  127. setState(() {
  128. _isComposing = false;
  129. });
  130.  
  131. await _ensureLoggedIn();
  132. _sendMessage(text: text);
  133. }
  134.  
  135. void _sendMessage({ String text, String imageUrl }) {
  136. reference.push().set({
  137. 'text': text,
  138. 'imageUrl': imageUrl,
  139. 'senderName': googleSignIn.currentUser.displayName,
  140. 'senderPhotoUrl': googleSignIn.currentUser.photoUrl,
  141. });
  142.  
  143. // ChatMessage message = new ChatMessage(
  144. // text: text,
  145. // animationController: new AnimationController(
  146. // duration: new Duration(milliseconds: 700),
  147. // vsync: this,
  148. // ),
  149. // );
  150.  
  151. // setState(() { _messages.insert(0, message); });
  152. // message.animationController.forward();
  153.  
  154. analytics.logEvent(name: "send_message");
  155. }
  156.  
  157. Widget _buildTextComposer() {
  158. return new IconTheme(
  159. data: new IconThemeData(color: Theme.of(context).accentColor),
  160. child: new Container(
  161. margin: const EdgeInsets.symmetric(horizontal: 8.0),
  162. child: new Row(
  163. children: <Widget>[
  164. new Container(
  165. margin: const EdgeInsets.symmetric(horizontal: 8.0),
  166. child: new IconButton(
  167. icon: new Icon(Icons.photo_camera),
  168. onPressed: () async {
  169. await _ensureLoggedIn();
  170. File imageFile = await ImagePicker.pickImage(source: ImageSource.gallery);
  171. int random = new Random().nextInt(100000);
  172. StorageReference ref = FirebaseStorage.instance.ref().child("image_$random.jpg");
  173. StorageUploadTask uploadTask = ref.putFile(imageFile);
  174. Uri downloadUrl = (await uploadTask.future).downloadUrl;
  175. _sendMessage(imageUrl: downloadUrl.toString());
  176. },
  177. ),
  178. ),
  179. new Flexible(
  180. child: new TextField(
  181. controller: _textController,
  182. onChanged: (String text) {
  183. setState(() {
  184. _isComposing = text.length > 0;
  185. });
  186. },
  187. onSubmitted: _handleSubmitted,
  188. decoration: new InputDecoration.collapsed(
  189. hintText: "Send a message",
  190. ),
  191. ),
  192. ),
  193. new Container(
  194. margin: new EdgeInsets.symmetric(horizontal: 4.0),
  195. child: Theme.of(context).platform == TargetPlatform.iOS ?
  196. new CupertinoButton(
  197. child: new Text("Send"),
  198. onPressed: _isComposing
  199. ? () => _handleSubmitted(_textController.text) : null,
  200. )
  201. :
  202. new IconButton(
  203. icon: new Icon(Icons.send),
  204. onPressed: _isComposing
  205. ? () => _handleSubmitted(_textController.text) : null,
  206. ),
  207. ),
  208. ],
  209. ),
  210. ),
  211. );
  212. }
  213.  
  214. @override
  215. Widget build(BuildContext context) {
  216. return new Scaffold(
  217. appBar: new AppBar(
  218. title: new Text("Friendlychat"),
  219. elevation: Theme.of(context).platform == TargetPlatform.iOS ? 0.0 : 4.0,
  220. ),
  221. body: new Column(
  222. children: <Widget>[
  223. new Flexible(
  224. child: new FirebaseAnimatedList(
  225. query: reference,
  226. sort: (a, b) => b.key.compareTo(a.key),
  227. padding: new EdgeInsets.all(8.0),
  228. reverse: true,
  229. itemBuilder: (_, DataSnapshot snapshot, Animation<double> animation, int index) {
  230. return new ChatMessage(
  231. snapshot: snapshot,
  232. animation: animation,
  233. );
  234. },
  235. ),
  236. ),
  237. new Divider(height: 1.0),
  238. new Container(
  239. decoration: new BoxDecoration(color: Theme.of(context).cardColor),
  240. child: _buildTextComposer(),
  241. ),
  242. ],
  243. ),
  244. );
  245. }
  246. }
Add Comment
Please, Sign In to add comment