Advertisement
alvinvin00

disaster_add.dart

Mar 18th, 2019
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Dart 7.80 KB | None | 0 0
  1. import 'package:flutter/material.dart';
  2. import 'dart:io';
  3. import 'package:firebase_database/firebase_database.dart';
  4. import 'package:firebase_storage/firebase_storage.dart';
  5. import 'package:firebase_auth/firebase_auth.dart';
  6. import 'package:image_picker/image_picker.dart';
  7. import 'dart:async';
  8.  
  9. import 'package:bencana/home.dart';
  10.  
  11. class DisasterAdd extends StatefulWidget {
  12.   @override
  13.   _DisasterAddState createState() => _DisasterAddState();
  14. }
  15.  
  16. class _DisasterAddState extends State<DisasterAdd> {
  17.   String userId;
  18.   String contentText;
  19.   String titleText;
  20.   var disasterId;
  21.   final contentController = TextEditingController();
  22.   final titleController = TextEditingController();
  23.   final locationController = TextEditingController();
  24.   File _imageFile;
  25.   File _image;
  26.   int timestamp;
  27.   bool isLoading = false;
  28.  
  29.   // Image untuk preview
  30.   Image buildImage() {
  31.     return Image.file(
  32.       _imageFile,
  33.       width: MediaQuery.of(context).size.width,
  34.       height: 240.0,
  35.       fit: BoxFit.fitWidth,
  36.     );
  37.   }
  38.  
  39.   // Upload image ke Firebase Storage
  40.   Future<String> uploadImage(var imageFile) async {
  41.     timestamp = DateTime.now().millisecondsSinceEpoch;
  42.     String fileName = timestamp.toString() + "jpg";
  43.     StorageReference storageRef =
  44.         FirebaseStorage.instance.ref().child('images').child(fileName);
  45.     StorageUploadTask task = storageRef.putFile(_image);
  46.     var _downloadUrl = await (await task.onComplete).ref.getDownloadURL();
  47.     String _url = _downloadUrl.toString();
  48.     print('Download URL: $_url');
  49.     return _url;
  50.   }
  51.  
  52.   // Simpan posting
  53.   void _postSave() async {
  54.     setState(() {
  55.       isLoading = true;
  56.     });
  57.  
  58.     await FirebaseAuth.instance.currentUser().then((user) {
  59.       userId = user.uid;
  60.     });
  61.     if (_image != null) {
  62.       print('Uploading image....');
  63.       uploadImage(_image).then((_url) {
  64.         if (_url != null) {
  65.           print('Image upload is successful!');
  66.           print('Image URL: $_url');
  67.           var postRef =
  68.               FirebaseDatabase.instance.reference().child('disasters');
  69.           try {
  70.             print('Saving post....');
  71.             disasterId = postRef.push().key;
  72.             postRef.child(disasterId).set({
  73.               'disasterId': disasterId,
  74.               'timestamp': timestamp,
  75.               'title': titleController.text,
  76.               'content': contentController.text,
  77.               'location': locationController.text,
  78.               'photo': _url.toString(),
  79.               'userId': userId
  80.             }).whenComplete(() {
  81.               print('Saving complete!');
  82.               titleController.clear();
  83.               contentController.clear();
  84.               Navigator.pop(
  85.                 context,
  86.                 MaterialPageRoute(builder: (context) => HomePage()),
  87.               );
  88.             });
  89.           } catch (e) {
  90.             setState(() {
  91.               isLoading = false;
  92.             });
  93.             print('Error1: $e');
  94.           }
  95.         } else {
  96.           setState(() {
  97.             isLoading = false;
  98.           });
  99.           print('Upload is not successful!');
  100.         }
  101.       });
  102.     } else {
  103.       var postRef = FirebaseDatabase.instance.reference().child('disasters');
  104.       try {
  105.         postRef.push().set({
  106.           'title': titleController.text,
  107.           'content': contentController.text,
  108.         }).whenComplete(() {
  109.           titleController.clear();
  110.           contentController.clear();
  111.           Navigator.pop(
  112.             context,
  113.             MaterialPageRoute(builder: (context) => HomePage()),
  114.           );
  115.         });
  116.       } catch (e) {
  117.         setState(() {
  118.           isLoading = false;
  119.         });
  120.         print('Error2: $e');
  121.       }
  122.     }
  123.   }
  124.  
  125.   // Image picker untuk kamera
  126.   void _openCamera() async {
  127.     print('open camera...');
  128.     try {
  129.       _imageFile = await ImagePicker.pickImage(source: ImageSource.camera);
  130.       print('path: $_imageFile');
  131.       setState(() {
  132.         _image = _imageFile;
  133.       });
  134.     } catch (e) {
  135.       print('Error3: $e');
  136.     }
  137.   }
  138.  
  139.   // Image picker untuk gallery
  140.   void _openGallery() async {
  141.     print('open gallery...');
  142.     try {
  143.       _imageFile = await ImagePicker.pickImage(source: ImageSource.gallery);
  144.       print('galery path: $_imageFile');
  145.       setState(() {
  146.         _image = _imageFile;
  147.       });
  148.     } catch (e) {
  149.       print('Error4: $e');
  150.     }
  151.   }
  152.  
  153.   @override
  154.   Widget build(BuildContext context) {
  155.     return Scaffold(
  156.         appBar: AppBar(
  157.           title: Text('Disaster Add'),
  158.           actions: <Widget>[
  159.             IconButton(
  160.               icon: Icon(Icons.save),
  161.               color: Colors.white,
  162.               onPressed: _postSave,
  163.             )
  164.           ],
  165.         ),
  166.         body: ListView(
  167.           padding: EdgeInsets.all(16.0),
  168.           children: <Widget>[
  169.             Container(
  170.               child: Column(
  171.                 children: <Widget>[
  172.                   TextField(
  173.                     decoration: InputDecoration(
  174.                       labelText: 'Title',
  175.                       alignLabelWithHint: true,
  176.                       border: OutlineInputBorder(
  177.                         borderRadius: BorderRadius.circular(5.0),
  178.                       ),
  179.                     ),
  180.                     maxLength: 50,
  181.                     maxLines: 1,
  182.                     controller: titleController,
  183.                     textCapitalization: TextCapitalization.words,
  184. //                    onSubmitted: (value) => titleText = value,
  185.                   ),
  186.                   TextField(
  187.                     decoration: InputDecoration(
  188.                       labelText: 'Content',
  189.                       hintText: 'Write your post...',
  190.                       alignLabelWithHint: true,
  191.                       border: OutlineInputBorder(
  192.                         borderRadius: BorderRadius.circular(5.0),
  193.                       ),
  194.                     ),
  195.                     maxLength: 500,
  196.                     maxLines: 6,
  197.                     controller: contentController,
  198.                     textCapitalization: TextCapitalization.sentences,
  199. //                    onSubmitted: (value) => contentText = value,
  200.                   ),
  201.                   TextField(
  202.                     decoration: InputDecoration(
  203.                       labelText: 'Location',
  204.                       hintText: 'Location',
  205.                       alignLabelWithHint: true,
  206.                       border: OutlineInputBorder(
  207.                         borderRadius: BorderRadius.circular(5.0),
  208.                       ),
  209.                     ),
  210.                     controller: locationController,
  211.                     textCapitalization: TextCapitalization.words,
  212. //                    onSubmitted: (value) => contentText = value,
  213.                   ),
  214.                   Row(
  215.                     children: <Widget>[
  216.                       IconButton(
  217.                         icon: Icon(
  218.                           Icons.camera_alt,
  219.                           color: Colors.grey,
  220.                         ),
  221.                         onPressed: _openCamera,
  222.                       ),
  223.                       IconButton(
  224.                         icon: Icon(
  225.                           Icons.image,
  226.                           color: Colors.grey,
  227.                         ),
  228.                         onPressed: _openGallery,
  229.                       ),
  230.                       Container(
  231.                           height: 20,
  232.                           width: 20,
  233.                           child: isLoading == true
  234.                               ? CircularProgressIndicator()
  235.                               : Text('')),
  236.                     ],
  237.                   ),
  238.                   _imageFile != null ? buildImage() : Text(''),
  239.                 ],
  240.               ),
  241.             ),
  242.           ],
  243.         ));
  244.   }
  245. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement