Reputation:
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 ?
Upvotes: 1
Views: 63
Reputation: 8264
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);
Upvotes: 1