Upload Images on FireBase Code:
import 'dart:io'; import 'package:firebase_storage/firebase_storage.dart'; // For File Upload To Firestore import 'package:flutter/material.dart'; import 'package:image_picker/image_picker.dart'; // For Image Picker import 'package:path/path.dart' as Path; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'WallPaper Demo', theme: ThemeData( // This is the theme of your application. // // Try running your application with "flutter run". You'll see the // application has a blue toolbar. Then, without quitting the app, try // changing the primarySwatch below to Colors.green and then invoke // "hot reload" (press "r" in the console where you ran "flutter run", // or simply save your changes to "hot reload" in a Flutter IDE). // Notice that the counter didn't reset back to zero; the application // is not restarted. primarySwatch: Colors.blue, // This makes the visual density adapt to the platform that you run // the app on. For desktop platforms, the controls will be smaller and // closer together (more dense) than on mobile platforms. visualDensity: VisualDensity.adaptivePlatformDensity, ), home: MyHomePage(), ); } } class MyHomePage extends StatefulWidget { @override _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { File _image; String _uploadedFileURL; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Firestore File Upload'), ), body: Center( child: Column( children: <Widget>[ Text('Selected Image'), _image != null ? Image.asset( _image.path, height: 150, ) : Container(height: 150), _image == null ? RaisedButton( child: Text('Choose File'), onPressed: chooseFile, color: Colors.cyan, ) : Container(), _image != null ? RaisedButton( child: Text('Upload File'), onPressed: uploadFile, color: Colors.cyan, ) : Container(), _image != null ? RaisedButton( child: Text('Clear Selection'), // onPressed: clearSelection, ) : Container(), Text('Uploaded Image'), _uploadedFileURL != null ? Image.network( _uploadedFileURL, height: 150, ) : Container(), ], ), ), ); } Future chooseFile() async { await ImagePicker.pickImage(source: ImageSource.gallery).then((image) { setState(() { _image = image; }); }); } Future uploadFile() async { StorageReference storageReference = FirebaseStorage.instance .ref() .child('chats/${Path.basename(_image.path)}}'); StorageUploadTask uploadTask = storageReference.putFile(_image); await uploadTask.onComplete; print('File Uploaded'); storageReference.getDownloadURL().then((fileURL) { setState(() { _uploadedFileURL = fileURL; }); }); } }
Leave a Reply