Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import 'package:flutter/material.dart';
- import 'dart:io';
- import 'package:firebase_database/firebase_database.dart';
- import 'package:firebase_storage/firebase_storage.dart';
- import 'package:firebase_auth/firebase_auth.dart';
- import 'package:image_picker/image_picker.dart';
- import 'dart:async';
- import 'package:bencana/home.dart';
- class DisasterAdd extends StatefulWidget {
- @override
- _DisasterAddState createState() => _DisasterAddState();
- }
- class _DisasterAddState extends State<DisasterAdd> {
- String userId;
- String contentText;
- String titleText;
- var disasterId;
- final contentController = TextEditingController();
- final titleController = TextEditingController();
- final locationController = TextEditingController();
- File _imageFile;
- File _image;
- int timestamp;
- bool isLoading = false;
- // Image untuk preview
- Image buildImage() {
- return Image.file(
- _imageFile,
- width: MediaQuery.of(context).size.width,
- height: 240.0,
- fit: BoxFit.fitWidth,
- );
- }
- // Upload image ke Firebase Storage
- Future<String> uploadImage(var imageFile) async {
- timestamp = DateTime.now().millisecondsSinceEpoch;
- String fileName = timestamp.toString() + "jpg";
- StorageReference storageRef =
- FirebaseStorage.instance.ref().child('images').child(fileName);
- StorageUploadTask task = storageRef.putFile(_image);
- var _downloadUrl = await (await task.onComplete).ref.getDownloadURL();
- String _url = _downloadUrl.toString();
- print('Download URL: $_url');
- return _url;
- }
- // Simpan posting
- void _postSave() async {
- setState(() {
- isLoading = true;
- });
- await FirebaseAuth.instance.currentUser().then((user) {
- userId = user.uid;
- });
- if (_image != null) {
- print('Uploading image....');
- uploadImage(_image).then((_url) {
- if (_url != null) {
- print('Image upload is successful!');
- print('Image URL: $_url');
- var postRef =
- FirebaseDatabase.instance.reference().child('disasters');
- try {
- print('Saving post....');
- disasterId = postRef.push().key;
- postRef.child(disasterId).set({
- 'disasterId': disasterId,
- 'timestamp': timestamp,
- 'title': titleController.text,
- 'content': contentController.text,
- 'location': locationController.text,
- 'photo': _url.toString(),
- 'userId': userId
- }).whenComplete(() {
- print('Saving complete!');
- titleController.clear();
- contentController.clear();
- Navigator.pop(
- context,
- MaterialPageRoute(builder: (context) => HomePage()),
- );
- });
- } catch (e) {
- setState(() {
- isLoading = false;
- });
- print('Error1: $e');
- }
- } else {
- setState(() {
- isLoading = false;
- });
- print('Upload is not successful!');
- }
- });
- } else {
- var postRef = FirebaseDatabase.instance.reference().child('disasters');
- try {
- postRef.push().set({
- 'title': titleController.text,
- 'content': contentController.text,
- }).whenComplete(() {
- titleController.clear();
- contentController.clear();
- Navigator.pop(
- context,
- MaterialPageRoute(builder: (context) => HomePage()),
- );
- });
- } catch (e) {
- setState(() {
- isLoading = false;
- });
- print('Error2: $e');
- }
- }
- }
- // Image picker untuk kamera
- void _openCamera() async {
- print('open camera...');
- try {
- _imageFile = await ImagePicker.pickImage(source: ImageSource.camera);
- print('path: $_imageFile');
- setState(() {
- _image = _imageFile;
- });
- } catch (e) {
- print('Error3: $e');
- }
- }
- // Image picker untuk gallery
- void _openGallery() async {
- print('open gallery...');
- try {
- _imageFile = await ImagePicker.pickImage(source: ImageSource.gallery);
- print('galery path: $_imageFile');
- setState(() {
- _image = _imageFile;
- });
- } catch (e) {
- print('Error4: $e');
- }
- }
- @override
- Widget build(BuildContext context) {
- return Scaffold(
- appBar: AppBar(
- title: Text('Disaster Add'),
- actions: <Widget>[
- IconButton(
- icon: Icon(Icons.save),
- color: Colors.white,
- onPressed: _postSave,
- )
- ],
- ),
- body: ListView(
- padding: EdgeInsets.all(16.0),
- children: <Widget>[
- Container(
- child: Column(
- children: <Widget>[
- TextField(
- decoration: InputDecoration(
- labelText: 'Title',
- alignLabelWithHint: true,
- border: OutlineInputBorder(
- borderRadius: BorderRadius.circular(5.0),
- ),
- ),
- maxLength: 50,
- maxLines: 1,
- controller: titleController,
- textCapitalization: TextCapitalization.words,
- // onSubmitted: (value) => titleText = value,
- ),
- TextField(
- decoration: InputDecoration(
- labelText: 'Content',
- hintText: 'Write your post...',
- alignLabelWithHint: true,
- border: OutlineInputBorder(
- borderRadius: BorderRadius.circular(5.0),
- ),
- ),
- maxLength: 500,
- maxLines: 6,
- controller: contentController,
- textCapitalization: TextCapitalization.sentences,
- // onSubmitted: (value) => contentText = value,
- ),
- TextField(
- decoration: InputDecoration(
- labelText: 'Location',
- hintText: 'Location',
- alignLabelWithHint: true,
- border: OutlineInputBorder(
- borderRadius: BorderRadius.circular(5.0),
- ),
- ),
- controller: locationController,
- textCapitalization: TextCapitalization.words,
- // onSubmitted: (value) => contentText = value,
- ),
- Row(
- children: <Widget>[
- IconButton(
- icon: Icon(
- Icons.camera_alt,
- color: Colors.grey,
- ),
- onPressed: _openCamera,
- ),
- IconButton(
- icon: Icon(
- Icons.image,
- color: Colors.grey,
- ),
- onPressed: _openGallery,
- ),
- Container(
- height: 20,
- width: 20,
- child: isLoading == true
- ? CircularProgressIndicator()
- : Text('')),
- ],
- ),
- _imageFile != null ? buildImage() : Text(''),
- ],
- ),
- ),
- ],
- ));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement