Firebase 为什么有时候会将imageUrl保存在cloud firestore数据库中&;有时它不会被保存
我正在创建一个颤振应用程序,它将图像url存储在CloudFireStore数据库中,该url以图像的形式获取并显示在我的颤振应用程序中。问题在于图像url有时保存在数据库中,有时不保存。当它被保存时,抓取过程正常工作,当它未保存或未保存时,它将使用null msg返回一个错误值,如图所示 我不知道为什么有时数据被保存,有时数据未保存会发生这种情况 请参阅以下代码,以便在cloud firestore数据库中保存图像Firebase 为什么有时候会将imageUrl保存在cloud firestore数据库中&;有时它不会被保存,firebase,flutter,dart,google-cloud-firestore,Firebase,Flutter,Dart,Google Cloud Firestore,我正在创建一个颤振应用程序,它将图像url存储在CloudFireStore数据库中,该url以图像的形式获取并显示在我的颤振应用程序中。问题在于图像url有时保存在数据库中,有时不保存。当它被保存时,抓取过程正常工作,当它未保存或未保存时,它将使用null msg返回一个错误值,如图所示 我不知道为什么有时数据被保存,有时数据未保存会发生这种情况 请参阅以下代码,以便在cloud firestore数据库中保存图像 import 'package:intl/intl.dart'; import
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,
),
),
],
),
],
),
),
),
);
}
}
import'包:intl/intl.dart';
导入“dart:io”;
导入“包:cloud_firestore/cloud_firestore.dart”;
进口“包装:颤振/cupertino.dart”;
进口“包装:颤振/材料.省道”;
导入“包装:密苏里卡/副本.dart”;
导入“包:image_picker/image_picker.dart”;
导入“package:mi_card/widget/provider_widget.dart”;
导入“package:path/path.dart”作为路径;
导入“包:firebase_存储/firebase_存储.dart”;
导入“../sec.dart”;
类EditProductScreen扩展StatefulWidget{
@凌驾
_EditProductScreenState createState()=>\u EditProductScreenState();
}
类_EditProductScreenState扩展状态{
//用于从手机屏幕上选择图片
var样本图像;
Future captureImage()异步{
var tempImage=等待ImagePicker.pickImage(源:ImageSource.camera);
设置状态(){
sampleImage=tempImage;
});
字符串文件名=path.basename(sampleImage.path);
最终存储参考firebaseStorageRef=
FirebaseStorage.instance.ref().child('entry/student entry/'+文件名);
最终StorageUploadTask任务=
firebaseStorageRef.putFile(sampleImage);
var ImageUrl=await(await task.onComplete).ref.getDownloadURL();
url=ImageUrl.toString();
打印(“图像Url=“+Url”);
//saveToDatabase(url);
}
void saveToDatabase(url){
}
//用于打开相机并拍摄图片
Future getImage()异步{
var tempImage=等待ImagePicker.pickImage(源:ImageSource.gallery);
设置状态(){
sampleImage=tempImage;
});
字符串文件名=path.basename(sampleImage.path);
最终存储参考firebaseStorageRef=
FirebaseStorage.instance.ref().child('entry/student entry/'+文件名);
最终StorageUploadTask任务=
firebaseStorageRef.putFile(sampleImage);
var ImageUrl=await(await task.onComplete).ref.getDownloadURL();
url=ImageUrl.toString();
打印(“图像Url=“+Url”);
saveToDatabase(url);
}
最终_priceFocusNode=FocusNode();
final _formKey=GlobalKey();
final _firestore=firestore.instance;
字符串url;
var_initValues={
“标题”:“,
“描述”:“,
“价格”:“,
“imageUrl”:“,
};
var_isInit=真;
@凌驾
void didChangeDependencies(){
如果(_isInit){
final productId=ModalRoute.of(context).settings.arguments作为字符串;
}
_isInit=假;
super.didChangeDependencies();
}
@凌驾
无效处置(){
_priceFocusNode.dispose();
super.dispose();
}
void\u saveForm()异步{
final isValid=_formKey.currentState.validate();
如果(!isValid){
返回;
}
_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');
字符串日期=formattate.format(dbTimeKey);
字符串时间=formatTime.format(dbTimeKey);
final uid=wait Provider.of(context.auth.getCurrentUID();
//每个用户的集合引用
DocumentReference Collection=Firestore.instance.Collection('entry').document();
Collection.setData({
“进入时间”:时间,
“图像”:url,
});
导航器。推(
上下文
MaterialPage路由(生成器:(上下文)=>MyApp()),
);
}
列出_位置=['NA'、'1st year'、'2year'、'3year'、'4year'];//选项2
字符串\u选择的位置;
@凌驾
小部件构建(构建上下文){
var_blankFocusNode=新的FocusNode();
返回脚手架(
appBar:appBar(
背景颜色:Colors.blue,
标题:文本(“条目”),
标题:对,
领先:新
图标按钮(
图标:图标(图标。箭头返回),
颜色:颜色,白色,
已按下:(){
Navigator.pop(
上下文
MaterialPartnerRoute(生成器:(上下文)=>SecondRoute()),
);
},
),
行动:[
扁平按钮(
textColor:Colors.white,
onPressed:_saveForm,
子项:文本(“保存”),
),
],
),
背景颜色:Colors.blueAccent,
正文:手势检测器(
onTap:(){
FocusScope.of(上下文).requestFocus(_blankFocusNode);
},
孩子:表格(
键:_formKey,
子:ListView(
滚动方向:轴垂直,
儿童:[
大小盒子(
身高:20.0,
),
划船(
mainAxisAlignment:mainAxisAlignment.center,
儿童:[
对齐(
对齐:对齐.center,
孩子:圆环星(
半径:73,
背景颜色:Colors.white,
孩子:斜坡(
孩子:新尺寸的盒子(
宽度:125,
身高:125,
子:sampleImage!=null
?Image.file(
样本图像,
身高:108,
fit:BoxFit.fill,
)
:图标按钮(
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);