Flutter: Firebase storage download url - firebase

I am new to Flutter and I am trying to make a wallpaper app where I use Firebase to store my images. The app retrieves images from Firebase and the user can share and download the images to the device. I'm using image_gallery_saver package but I wasn't able to get the url of the images so I can add it to the image_gallery_saver function, is there a simple way to get the url of an image from firebase after the user clicks on a specific image?
The following is the home page:
import 'package:cardstest2/Screens/ImageScreen.dart';
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'dart:async';
class FirestoreListViewPage extends StatefulWidget {
#override
_FirestoreListViewPageState createState() => _FirestoreListViewPageState();
}
class _FirestoreListViewPageState extends State<FirestoreListViewPage> {
Future _data;
Future getPosts() async {
var firestore = Firestore.instance;
QuerySnapshot qn = await firestore.collection("gallery").getDocuments();
return qn.documents;
}
#override
void initState() {
super.initState();
_data = getPosts();
}
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: Text('Subcategories'),
),
body: Container(
child: FutureBuilder(
future: _data,
builder: (_, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(
child: Text('Waiting...'),
);
} else {
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (_, index){
return Card(
child: ListTile(
title: Image.network(snapshot.data[index].data['GalleryUrl']),
onTap: () {
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => imageScreenPage(snapshot.data[index].data['GalleryUrl']),
),
);
},
),
);
});
}
}),
),
);
}
}
The following is the imageScreen page:
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:share/share.dart';
import 'package:dio/dio.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'dart:ui';
class imageScreenPage extends StatefulWidget {
String cardPath;
imageScreenPage(this.cardPath);
#override
_imageScreenPageState createState() => _imageScreenPageState();
}
class _imageScreenPageState extends State<imageScreenPage> {
final LinearGradient backgroundGradient = new LinearGradient(
colors: [new Color(0x10000000), new Color(0x30000000)],
begin: Alignment.topLeft,
end: Alignment.bottomRight);
#override
Widget build(BuildContext context) {
return new Scaffold(
body: new SizedBox.expand(
child: new Container(
decoration: new BoxDecoration(gradient: backgroundGradient),
child: new Stack(
children: <Widget>[
new Align(
alignment: Alignment.center,
child: new Hero(
tag: widget.cardPath,
child: new Image.network(widget.cardPath),
),
),
new Align(
alignment: Alignment.topCenter,
child: new Column(
mainAxisAlignment: MainAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
new AppBar(
elevation: 0.0,
backgroundColor: Colors.transparent,
leading: new IconButton(
icon: new Icon(
Icons.close,
color: Colors.black,
),
onPressed: () => Navigator.of(context).pop()),
)
],
),
),
],
),
),
),
persistentFooterButtons: <Widget>[
IconButton(
icon: Icon(Icons.wallpaper), onPressed: () {},
),
IconButton(
icon: Icon(Icons.file_download), onPressed: () {_save();},
),
IconButton(
icon: Icon(Icons.share), onPressed: () {Share.share(widget.cardPath);},
),
],
);
}
_save() async {
var response = await Dio().get("<insert url>", options: Options(responseType: ResponseType.bytes));
final result = await ImageGallerySaver.saveImage(Uint8List.fromList(response.data));
print(result);
}
}

To get the downloadUrl, then do the following:
StorageTaskSnapshot snapshot = await storage
.ref()
.child("images/$imageName")
.putFile(file)
.onComplete;
if (snapshot.error == null) {
final String downloadUrl =
await snapshot.ref.getDownloadURL();
}
use putFile to add the file to Firebase Storage, then you can use snapshot.ref.getDownloadURL() to get the url.

For all the people using flutter in 2021
This worked for me
import 'package:firebase_storage/firebase_storage.dart' as firebase_storage;
Future<String> uploadImage(imageFile) async {
firebase_storage.Reference ref = storage.ref().child('post_$postId.jpg');
firebase_storage.UploadTask uploadTask = ref.putFile(imageFile);
print('File Uploaded');
var imageUrl = await (await uploadTask).ref.getDownloadURL();
String url = imageUrl.toString();
return url;
}
uploadImage() is a function which takes in an imageFile
You have to call it using await uploadImage(imageFile) inside an asynchronous function

Related

Firebase : Why appearing [clound_firestore/permission-denied] for my firestore

I know there is a lot of similar posts, but I still cannot find my own answer for my issue. Since I want to get the data from firebase without pressing the button and diretly can get the data from it, therefore I have used the StreamBuilder for my coding but I still get this error. Is this is my firestore database or realtime database permission get any wrong?
--Issue warning--
Below are my coding:
import 'dart:async';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:profile_staff/edit_profile_page.dart';
import 'package:profile_staff/profile_widget.dart';
import 'package:profile_staff/user.dart';
import 'package:profile_staff/user_preferences.dart';
class ProfilePage extends StatefulWidget {
const ProfilePage({Key? key}) : super(key: key);
#override
_ProfilePageState createState() => _ProfilePageState();
}
class _ProfilePageState extends State<ProfilePage> {
final Stream<QuerySnapshot> users =
FirebaseFirestore.instance.collection('users').snapshots();
TextEditingController _controller = TextEditingController();
void initState() {
super.initState();
}
#override
Widget build(BuildContext context) {
final user = UserPreferences.myUser;
return Scaffold(
appBar: AppBar(
leading: new IconButton(
onPressed: () {}, icon: new Icon(Icons.arrow_back_ios_sharp)),
title: Center(
child: Text(
'My Profile',
style: TextStyle(color: Colors.white),
),
),
actions: [
IconButton(
onPressed: () {
Navigator.of(context).push(
MaterialPageRoute(builder: (context) => EditProfilePage()),
);
},
icon: new Icon(Icons.create_outlined))
],
backgroundColor: Colors.green,
shadowColor: Colors.white,
elevation: 3,
),
body: Padding(
padding: const EdgeInsets.all(20.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Read Data',
style: TextStyle(fontSize: 20, fontWeight: FontWeight.w600),
),
Container(
height: 250,
padding: const EdgeInsets.symmetric(vertical: 20),
child: StreamBuilder<QuerySnapshot>(
stream: users,
builder: (
BuildContext context,
AsyncSnapshot<QuerySnapshot> snapshot,
) {
// if (!snapshot.hasData) {
// return Text('error404');
// }
if (snapshot.connectionState == ConnectionState.waiting) {
return Text('Loading');
}
final data = snapshot.requireData;
return ListView.builder(
itemCount: data.size,
itemBuilder: (context, index) {
return Text(
'My name is ${data.docs[index]['name']} and I am ${data.docs[index]['age']}');
},
);
},
))
],
),
}
My Firestore Database:
My Realtime Database:
enter image description here
enter image description here
I was facing same issue.Forgot to deploy/upload new rules

Update Flutter UI after changing data on Firebase Firestore

I have an app with a profile page with username, email, and profile picture.
What I am trying to do is, the user click on a button to change the profile picture, opening a new page with a simple Circle Avatar Widget and a button, which will upload the image to Firebase Storage and Firebase Firestore, adding to the Firestore collection of that specific current user uid.
Everything works fine, I can see the changes on the Firebase storage, the image being added by the uid + the URL on the current user collection.
This is the code of the edit_user_image_screen:
import 'dart:io';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:tradie_app/scr/providers/authService.dart';
import 'package:tradie_app/scr/widgets/loading.dart';
class EditCompanyImageScreen extends StatefulWidget {
#override
_EditCompanyImageScreenState createState() => _EditCompanyImageScreenState();
}
class _EditCompanyImageScreenState extends State<EditCompanyImageScreen> {
// Keep track of the form for validation
final _formKey = GlobalKey<FormState>();
// Loading Icon
bool loading = false;
final AuthService _authService = AuthService();
final FirebaseAuth _firebaseAuth = FirebaseAuth.instance;
final FirebaseFirestore _firebaseFirestore = FirebaseFirestore.instance;
File _image;
Future getImage(bool gallery) async {
ImagePicker picker = ImagePicker();
PickedFile pickedFile;
// Let user select photo from gallery
if (gallery) {
pickedFile = await picker.getImage(
source: ImageSource.gallery,
);
}
setState(() {
if (pickedFile != null) {
_image = File(pickedFile.path);
uploadFile(_image); // Use if you only need a single picture
} else {
print('No image selected.');
}
});
}
Future<String> uploadFile(File image) async {
String downloadURL;
Reference ref = FirebaseStorage.instance
.ref()
.child("images/${_firebaseAuth.currentUser.uid}");
await ref.putFile(image);
downloadURL = await ref.getDownloadURL();
return downloadURL;
}
Future uploadToFirebase() async {
final CollectionReference users =
_firebaseFirestore.collection("Companies");
final String uid = _firebaseAuth.currentUser.uid;
String url = await uploadFile(
_image); // this will upload the file and store url in the variable 'url'
await users.doc(uid).update({'url': url});
final result = await users.doc(uid).get();
return result.data()["url"];
}
#override
Widget build(BuildContext context) {
return loading
? Loading()
: Scaffold(
appBar: AppBar(
title: Text("Update Profile Image"),
),
body: Form(
key: _formKey,
child: Column(
children: [
Container(
child: Stack(
children: <Widget>[
Align(
alignment: Alignment.center,
child: IconButton(
icon: Icon(Icons.camera_alt),
onPressed: () async {
getImage(true);
},
),
),
Container(
child: _image != null
? Container(
height: 200,
width: 200,
decoration: BoxDecoration(
image: DecorationImage(
image: FileImage(
_image,
),
fit: BoxFit.contain),
),
)
: Container(
decoration: BoxDecoration(
color: Colors.grey[200],
borderRadius: BorderRadius.circular(50),
),
width: 100,
height: 100,
child: Icon(
Icons.camera_alt,
color: Colors.grey[800],
),
),
),
],
),
),
Row(
children: [
ElevatedButton(
style: ElevatedButton.styleFrom(
primary: Colors.black,
),
child: Text(
"Submit",
style: TextStyle(color: Colors.white),
),
onPressed: () async {
uploadToFirebase();
Navigator.pop(context);
},
),
],
),
],
),
),
);
}
}
And on the company_profile_screen, I have this snippet of code:
Stream getCompanyImageData() async* {
final CollectionReference users =
_firebaseFirestore.collection("Companies");
final String uid = _firebaseAuth.currentUser.uid;
final result = await users.doc(uid).get();
yield result.data()["url"];
}
My problem:
When I go back from edit_user_image_screen to company_screen, the App UI is not updating, I can see the changes on Firebase, and if I reload Android Studio, I can see the changes on the UI, but not automatically.
Here is the code where I am displaying the image on the company_screen:
Column(
children: [
StreamBuilder(
stream: getCompanyImageData(),
builder: (BuildContext context,
AsyncSnapshot snapshot) {
if (snapshot.connectionState ==
ConnectionState.waiting) {
return Center(
child: CircularProgressIndicator(),
);
}
return Image.network(
snapshot.data.toString(),
width: 100,
height: 100,
);
},
),
],
),
Try it like this, and cancel your top function getCompanyImageData()
Column(children: [
StreamBuilder(
stream: _firebaseFirestore.collection("Companies").doc(_firebaseAuth.currentUser.uid).snapshots(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(
child: CircularProgressIndicator(),
);
}
return Image.network(
snapshot.data.data()["url"],
width: 100,
height: 100,
);
},
),
This would depend on your state management,
CollectionRef.users.doc(ViewModelUser.user.value.mobile).snapshots().listen((event) {
ViewModelUser.setUser(UserModel.fromJson(event.data()));
});
This is my code where I listen for changes in my profile, when there is a change firebase sends me the updated data and I update my userData, my state management does the rest of updating the UI.

The argument type 'UserResult' can't be assigned to the parameter type 'UserSearch'

I am trying to make a search functionality that will help a user search for another user. I have created a stateful widget UserSearch and a stateless Widget UserResult. UserSearch builds the results based on UserResult's data. However I am unable to pass UserResult as an argument in UserSearch and I have no clue why. Any help will be great. Thanks in advance
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:vibing_app/feed.dart';
import 'package:vibing_app/model/user.dart';
class UserSearch extends StatefulWidget {
#override
_UserSearchState createState() => _UserSearchState();
}
class _UserSearchState extends State<UserSearch> {
final userRef = FirebaseFirestore.instance.collection('user');
TextEditingController searchController = new TextEditingController();
Future<QuerySnapshot> searchResults;
handleSearch(String query)
{
Future<QuerySnapshot> users = userRef.where("first_name"+ "last_name", isGreaterThanOrEqualTo: query).get();
setState(() {
searchResults = users;
});
}
clearSearch()
{
searchController.clear();
}
AppBar buildSearchField()
{
return AppBar(
backgroundColor: Colors.yellow,
title: TextFormField(
controller: searchController,
decoration: InputDecoration(
hintText: "Search for a user",
filled: true,
suffixIcon: IconButton(
icon: Icon(Icons.clear),
onPressed: clearSearch,
),
),
onFieldSubmitted: handleSearch,
),
);
}
Container searchContainer(){
final Orientation orientation = MediaQuery.of(context).orientation;
return Container(
child: Center(
child: ListView(
shrinkWrap: true,
children: [
Text("Find users...",
textAlign: TextAlign.center,
),
],
),
),
);
}
buildSearchResults()
{
return FutureBuilder(
future: searchResults,
builder: (context, snapshot){
if(!snapshot.hasData)
return CircularProgressIndicator();
List<UserSearch> searchResults = [];
snapshot.data.forEach((docu){
AppUser user = AppUser.fromDocument(docu);
UserResult searchResult = UserResult(user);
searchResults.add(UserResult(user)); //This part is giving me the error
});
return ListView(
children: searchResults,
);
},
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: buildSearchField(),
body:
searchResults == null ? searchContainer(): buildSearchResults(),
);
}
}
class UserResult extends StatelessWidget {
final AppUser user;
UserResult(this.user);
#override
Widget build(BuildContext context) {
return Container(
child: Column(
children: [
GestureDetector(
onTap: showUserProfile(context,profileID: user.userId),
child: ListTile(
leading: CircleAvatar(
backgroundColor: Colors.yellow,
backgroundImage: Image.network(user.photoURL).image,
),
title: Text(user.firstName + " " + user.lastName),
),
),
Divider(
height: 2.0,
color: Colors.white54,
),
],
),
);
}
}
It is a different types. You need to change List type to UserList:
List<UserResult> searchResults = [];

How to save user data in cloud fire store in flutter

I am using a package called lit_firebase_auth which makes firebase authentication easier to handle. I want to be able to save user data, such as the username after the user logs in. Basically as such:
User logs in or signs up --> User clicks on edit profile page from the home screen --> User can enter their desired name in the text field and click save --> Saves this data to the cloud of the respectful logged in user.
Please I'm a beginner and I have no idea how to pull this off.
Here is the code for reference:
cloud_firebase.dart:
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
Future<void> userSetup(String displayName) async {
CollectionReference users = FirebaseFirestore.instance.collection('Users');
FirebaseAuth auth = FirebaseAuth.instance;
String uid = auth.currentUser.uid.toString();
users.add({'displayName': displayName, 'uid': uid});
return;
}
auth.dart
import 'package:flutter/material.dart';
import 'package:kiwi/screens/auth/register.dart';
import 'package:kiwi/screens/background_painter.dart';
import 'package:lit_firebase_auth/lit_firebase_auth.dart';
import 'package:kiwi/screens/auth/sign_in.dart';
import 'package:animations/animations.dart';
import 'package:kiwi/screens/home.dart';
class AuthScreen extends StatefulWidget {
const AuthScreen({Key key}) : super(key: key);
static MaterialPageRoute get route => MaterialPageRoute(
builder: (context) => const AuthScreen(),
);
#override
_AuthScreenState createState() => _AuthScreenState();
}
class _AuthScreenState extends State<AuthScreen>
with SingleTickerProviderStateMixin {
AnimationController _controller;
ValueNotifier<bool> showSignInPage = ValueNotifier<bool>(true);
#override
void initState() {
_controller =
AnimationController(vsync: this, duration: const Duration(seconds: 2));
super.initState();
}
#override
void dispose() {
_controller.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: LitAuth.custom(
onAuthSuccess: () {
Navigator.of(context).pushReplacement(HomeScreen.route);
},
child: Stack(
children: [
SizedBox.expand(
child: CustomPaint(
painter: BackgroundPainter(),
)),
Center(
child: ConstrainedBox(
constraints: BoxConstraints(maxWidth: 800),
child: ValueListenableBuilder<bool>(
valueListenable: showSignInPage,
builder: (context, value, child) {
return PageTransitionSwitcher(
reverse: !value,
duration: Duration(milliseconds: 800),
transitionBuilder:
(child, animation, secondaryAnimation) {
return SharedAxisTransition(
animation: animation,
secondaryAnimation: secondaryAnimation,
transitionType: SharedAxisTransitionType.vertical,
fillColor: Colors.transparent,
child: child,
);
},
child: value
? SignIn(
key: ValueKey('SignIn'),
onRegisterClicked: () {
context.resetSignInForm();
showSignInPage.value = false;
_controller.forward();
},
)
: Register(
key: ValueKey('Register'),
onSignInPressed: () {
context.resetSignInForm();
showSignInPage.value = true;
_controller.reverse();
},
),
);
},
),
),
),
],
),
),
);
}
}
splash.dart
import 'package:flutter/material.dart';
import 'package:lit_firebase_auth/lit_firebase_auth.dart';
import 'package:kiwi/screens/home.dart';
import 'package:kiwi/screens/auth/auth.dart';
class SplashScreen extends StatelessWidget {
const SplashScreen({Key key}) : super(key: key);
static MaterialPageRoute get route => MaterialPageRoute(
builder: (context) => const SplashScreen(),
);
#override
Widget build(BuildContext context) {
final user = context.watchSignedInUser();
user.map(
(value) {
_navigateToHomeScreen(context);
},
empty: (_) {
_navigateToAuthScreen(context);
},
initializing: (_) {},
);
return const Scaffold(
body: Center(
child: CircularProgressIndicator(),
),
);
}
void _navigateToAuthScreen(BuildContext context) {
WidgetsBinding.instance.addPostFrameCallback(
(_) => Navigator.of(context).pushReplacement(AuthScreen.route),
);
}
void _navigateToHomeScreen(BuildContext context) {
WidgetsBinding.instance.addPostFrameCallback(
(_) => Navigator.of(context).pushReplacement(HomeScreen.route),
);
}
}
edit_profile.dart
import 'package:flutter/material.dart';
import 'package:kiwi/config/palette.dart';
import 'package:kiwi/screens/auth/decoration_functions.dart';
class Profile extends StatefulWidget {
const Profile({Key key}) : super(key: key);
static MaterialPageRoute get route => MaterialPageRoute(
builder: (context) => const Profile(),
);
_ProfileState createState() => _ProfileState();
}
class _ProfileState extends State<Profile> {
// UserModel _currentUser = locator.get<UserController>().currentUser;
// File _image;
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
title: Text('Edit Profile'),
),
body: Builder(
builder: (context) => Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
SizedBox(
height: 20.0,
),
Column(
children: <Widget>[
Text(
'Hey there',
style: TextStyle(color: Palette.lightGreen, fontSize: 20),
)
],
),
SizedBox(
height: 20,
),
Expanded(
flex: 8,
child: ListView(
children: [
Padding(
padding: EdgeInsets.fromLTRB(50, 0, 50, 0),
child: TextFormField(
style: const TextStyle(
fontSize: 18,
color: Colors.green,
),
decoration: signInInputDecoration(
hintText: 'New Username',
),
),
),
SizedBox(
height: 20,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
RaisedButton(
elevation: 4,
color: Colors.red,
onPressed: () {
Navigator.of(context).pop();
},
child: const Text(
'Cancel',
style: TextStyle(color: Colors.white),
),
),
RaisedButton(
elevation: 4,
color: Palette.lightGreen,
onPressed: () {
Navigator.of(context).pop();
},
child: const Text(
'Save',
style: TextStyle(color: Colors.white),
),
),
],
),
],
),
),
],
),
),
),
);
}
}
to save user data to document in firebase using uuid for document name the below code will work.
if you are confused about how to use the code in your app its simple.
just follow the steps:
call userSetup Function from onpress while passing the display name data.
how to use
the below code will create new document using the currect users uuid in firestore in user collection and save the data.
onPress:(){
userSetup(displayName:"zakriakhan");
}
userSteup Function
Future<void> userSetup(String displayName) async {
//firebase auth instance to get uuid of user
FirebaseAuth auth = FirebaseAuth.instance.currentUser();
//now below I am getting an instance of firebaseiestore then getting the user collection
//now I am creating the document if not already exist and setting the data.
FirebaseFirestore.instance.collection('Users').document(auth.uid).setData(
{
'displayName': displayName, 'uid': uid
})
return;
}

why sometime the imageUrl get saved inside cloud firestore database & sometime it does not get saved

I am creating a flutter application which will store Image-url inside cloud firestore database and that url get fetched in the form of image and display inside my flutter application. The problem is with image-url sometime it is get saved inside the database and sometime it does not. When it get saved the fetching process work properly and when it does not saved or unsaved it will reture a error value with null msg which is shown in the image.
I don't know why this is happening sometime the data get saved and sometime it is unsaved.
Pls see the below code for saving of Image inside the cloud firestore database.
import 'package:intl/intl.dart';
import 'dart:io';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:mi_card/duplicate.dart';
import 'package:image_picker/image_picker.dart';
import 'package:mi_card/widget/provider_widget.dart';
import 'package:path/path.dart' as path;
import 'package:firebase_storage/firebase_storage.dart';
import '../sec.dart';
class EditProductScreen extends StatefulWidget {
#override
_EditProductScreenState createState() => _EditProductScreenState();
}
class _EditProductScreenState extends State<EditProductScreen> {
//for selecting picture from galary of phone
var sampleImage;
Future captureImage() async {
var tempImage = await ImagePicker.pickImage(source: ImageSource.camera);
setState(() {
sampleImage = tempImage;
});
String fileName = path.basename(sampleImage.path);
final StorageReference firebaseStorageRef =
FirebaseStorage.instance.ref().child('entry/student entry/'+fileName);
final StorageUploadTask task =
firebaseStorageRef.putFile(sampleImage);
var ImageUrl= await(await task.onComplete).ref.getDownloadURL();
url=ImageUrl.toString();
print("Image Url="+url);
//saveToDatabase(url);
}
void saveToDatabase(url){
}
//for camera opening and capturing the picture
Future getImage() async {
var tempImage = await ImagePicker.pickImage(source: ImageSource.gallery);
setState(() {
sampleImage = tempImage;
});
String fileName = path.basename(sampleImage.path);
final StorageReference firebaseStorageRef =
FirebaseStorage.instance.ref().child('entry/student entry/'+fileName);
final StorageUploadTask task =
firebaseStorageRef.putFile(sampleImage);
var ImageUrl= await(await task.onComplete).ref.getDownloadURL();
url=ImageUrl.toString();
print("Image Url="+url);
saveToDatabase(url);
}
final _priceFocusNode = FocusNode();
final _formKey = GlobalKey<FormState>();
final _firestore = Firestore.instance;
String url;
var _initValues = {
'title': '',
'description': '',
'price': '',
'imageUrl': '',
};
var _isInit = true;
#override
void didChangeDependencies() {
if (_isInit) {
final productId = ModalRoute.of(context).settings.arguments as String;
}
_isInit = false;
super.didChangeDependencies();
}
#override
void dispose() {
_priceFocusNode.dispose();
super.dispose();
}
void _saveForm() async{
final isValid = _formKey.currentState.validate();
if (!isValid) {
return;
}
_formKey.currentState.save();
var dbTimeKey = new DateTime.now();
var formatDate=new DateFormat('dd/MMMM/yyyy');
var formatTime=new DateFormat('dd/MMMM/yyyy &'' hh:mm aaa, EEEE');
String date = formatDate.format(dbTimeKey);
String time = formatTime.format(dbTimeKey);
final uid = await Provider.of(context).auth.getCurrentUID();
// collection reference for every user
DocumentReference Collection = Firestore.instance.collection(' entry').document();
Collection.setData({
"Entry-time": time,
'image': url,
});
Navigator.push(
context,
MaterialPageRoute(builder: (context) => MyApp()),
);
}
List<String> _locations = ['NA','1st year', '2 year', '3 year', '4 year']; // Option 2
String _selectedLocation;
#override
Widget build(BuildContext context) {
var _blankFocusNode = new FocusNode();
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.blue,
title: Text('ENTRY'),
centerTitle: true,
leading: new
IconButton(
icon: Icon(Icons.arrow_back),
color: Colors.white,
onPressed: () {
Navigator.pop(
context,
MaterialPageRoute(builder: (context) => SecondRoute()),
);
},
),
actions: <Widget>[
FlatButton(
textColor: Colors.white,
onPressed: _saveForm,
child: Text("Save",),
),
],
),
backgroundColor: Colors.blueAccent,
body: GestureDetector (
onTap: () {
FocusScope.of(context).requestFocus(_blankFocusNode);
},
child: Form(
key: _formKey,
child: ListView(
scrollDirection: Axis.vertical,
children: <Widget>[
SizedBox(
height: 20.0,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Align(
alignment: Alignment.center,
child: CircleAvatar(
radius:73 ,
backgroundColor: Colors.white,
child: ClipOval(
child: new SizedBox(
width: 125,
height:125,
child: sampleImage != null
? Image.file(
sampleImage,
height: 108,
fit: BoxFit.fill,
)
: IconButton(
icon: Icon(
Icons.person,
color: Colors.grey[400],
),
iconSize: 80.0,
//onPressed:_takePicture
),
),
),
),
),
Padding(
padding: EdgeInsets.only(top: 0.0),
child: IconButton(
icon: Icon(
Icons.camera_alt,
color: Colors.black,
size: 30.0,
),
onPressed: captureImage,
),
),
Padding(
padding: EdgeInsets.only(top: 00.0),
child: IconButton(
icon: Icon(
Icons.folder,
color: Colors.orangeAccent[100],
size: 30.0,
),
onPressed: getImage,
),
),
],
),
],
),
),
),
);
}
}
How to handle this error ?
Here is a better approach to uploading images to storage and getting url back
final StorageReference storageReference =
FirebaseStorage().ref().child("path/$name");
final StorageUploadTask uploadTask =
storageReference.putFile(imaeFile);
final StreamSubscription<StorageTaskEvent> streamSubscription =
uploadTask.events.listen((event) {
// You can use this to notify yourself or your user in any kind of way.
// For example: you could use the uploadTask.events stream in a StreamBuilder instead
// to show your user what the current status is. In that case, you would not need to cancel any
// subscription as StreamBuilder handles this automatically.
print('EVENT ${event.type}');
});
// Cancel your subscription when done.
await uploadTask.onComplete;
streamSubscription.cancel();
String url =
await (await uploadTask.onComplete).ref.getDownloadURL();
saveToDatabase(url);

Resources