如何解决将多张图片上传到 Firestore 时出错
我在使此代码正常工作时遇到问题。我反复查看了代码中的错误,但我没有发现任何错误。我的猜测是问题可能出在我的互联网连接上,但我想加倍确定。
有人可以帮我检查我的代码吗,很可能我做错了什么。
首先,在正文部分,应该显示用户的个人资料图片。它显示一个错误(“profilePic was called on null”)。我不知道为什么;
leading: CircleAvatar(
backgroundImage:
CachednetworkImageProvider(widget.user.profilePic),),
此外,当我尝试上传多张图片时,只会上传第一张图片,并且不会在 Cloud Firestore 中自动创建集合。
请参阅下面的完整代码。我真的很感激这里有人的帮助;
final postsReference = FirebaseFirestore.instance.collection("posts");
final StorageReference storageReference =
FirebaseStorage.instance.ref().child("Uploads");
class PhotoUpload extends StatefulWidget {
final z.User user;
PhotoUpload({this.user});
@override
_PhotoUploadState createState() => _PhotoUploadState();
}
class _PhotoUploadState extends State<PhotoUpload>
with AutomaticKeepAliveClientMixin<PhotoUpload> {
List<File> _image = [];
final picker = ImagePicker();
String postId = Uuid().v4();
bool uploading = false;
TextEditingController descriptionTextEditingController =
TextEditingController();
TextEditingController locationTextEditingController = TextEditingController();
bool get wantKeepAlive => true;
@override
Widget build(BuildContext context) {
return Scaffold(
floatingActionButton: FloatingActionButton(
backgroundColor: Colors.purple,onpressed: () => controlImageUpload(),child: Icon(
Icons.send,size: 32,color: Colors.white,appBar: AppBar(
backgroundColor: Colors.purple,centerTitle: true,title: Text(
"Image Upload",style: TextStyle(
fontSize: 20.0,fontWeight: FontWeight.bold),body: Column(
children: <Widget>[
uploading ? linearProgress() : Text(""),Expanded(
child: GridView.builder(
itemCount: _image.length + 1,gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3),itemBuilder: (context,index) {
return index == 0
? Column(
mainAxisAlignment: MainAxisAlignment.center,children: <Widget>[
IconButton(
icon: Icon(Icons.camera_alt,color: Colors.purple,size: 40.0),onpressed: () =>
!uploading ? captureImage(context) : null,Padding(
padding: const EdgeInsets.all(2.0),child: RaisedButton(
shape: RoundedRectangleBorder(
borderRadius:
BorderRadius.circular(35.0)),child: Text(
"Load Image",style: TextStyle(
color: Colors.white,fontSize: 14.0),onpressed: () => captureImage(context),])
: Container(
margin: EdgeInsets.all(3),decoration: Boxdecoration(
image: decorationImage(
image: FileImage(_image[index - 1]),fit: BoxFit.cover)),);
}),ListTile(
leading: CircleAvatar(
backgroundImage:
CachednetworkImageProvider(widget.user.profilePic),title: Container(
width: 250.0,child: TextField(
style: TextStyle(color: Colors.black),controller: descriptionTextEditingController,decoration: Inputdecoration(
hintText: "Say something!",hintStyle: TextStyle(color: Colors.grey),border: InputBorder.none,Divider(),ListTile(
leading: Icon(
Icons.person_pin_circle,size: 36,controller: locationTextEditingController,decoration: Inputdecoration(
hintText: "Add location",Container(
width: 220,height: 50,alignment: Alignment.center,child: RaisedButton.icon(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(35)),icon: Icon(
Icons.location_on,label: Text(
"Get my location",style: TextStyle(color: Colors.white),onpressed: getUserCurrentLocation,],);
}
upLoadImageFromgallery() async {
final pickedFile = await picker.getimage(source: ImageSource.gallery);
setState(() {
_image.add(File(pickedFile?.path));
});
if (pickedFile.path == null) {
retrieveLostData();
}
}
captureImageWithCamera() async {
final pickedFile = await picker.getimage(source: ImageSource.camera);
setState(() {
_image.add(File(pickedFile?.path));
});
if (pickedFile.path == null) {
retrieveLostData();
}
}
captureImage(mContext) {
return showDialog(
context: mContext,builder: (context) {
return simpledialog(
title: Text("New Upload",style:
TextStyle(color: Colors.grey,fontWeight: FontWeight.bold)),children: <Widget>[
simpledialogOption(
child: Text("Capture with Camera",style: TextStyle(color: Colors.grey)),onpressed: captureImageWithCamera,simpledialogOption(
child: Text("Select from gallery",onpressed: upLoadImageFromgallery,simpledialogOption(
child: Text("Done",onpressed: () => Navigator.pop(context),);
});
}
Future<void> retrieveLostData() async {
final LostData response = await picker.getLostData();
if (response.isEmpty) {
return;
}
if (response.file != null) {
setState(() {
_image.add(File(response.file.path));
});
} else {
print(response.file);
}
}
Future<String> uploadPhoto() async {
for (var img in _image) {
StorageUploadTask mStorageUploadTask = storageReference
.child('images/${Path.basename(img.path)}')
.putFile(img);
StorageTaskSnapshot storageTaskSnapshot =
await mStorageUploadTask.onComplete;
String downloadUrl = await storageTaskSnapshot.ref.getDownloadURL();
return downloadUrl;
}
}
getUserCurrentLocation() async {
Position position = await Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.high);
List<Placemark> placeMarks =
await placemarkFromCoordinates(position.latitude,position.longitude);
Placemark mPlaceMark = placeMarks[0];
String completeAddressInfo =
'${mPlaceMark.subThoroughfare} ${mPlaceMark.thoroughfare},${mPlaceMark.subLocality} ${mPlaceMark.locality},${mPlaceMark.subAdministrativeArea} ${mPlaceMark.administrativeArea},${mPlaceMark.postalCode} ${mPlaceMark.country},';
String cityStateCountry =
'${mPlaceMark.subLocality},${mPlaceMark.locality},${mPlaceMark.country}';
locationTextEditingController.text = cityStateCountry;
}
saveImageInfoToFireStore({String url,String location,String description}) {
postsReference
.doc(widget.user.id)
.collection("postimages")
.doc(postId)
.set({
"postId": postId,"ownerId": widget.user.id,"timestamp": timestamp,"likes": {},"dislikes": {},"username": widget.user.username,"description": description,"location": location,"url": url,});
}
controlImageUpload() async {
setState(() {
uploading = true;
});
String downloadUrl = await uploadPhoto();
saveImageInfoToFireStore(
url: downloadUrl,location: locationTextEditingController.text,description: descriptionTextEditingController.text);
locationTextEditingController.clear();
descriptionTextEditingController.clear();
setState(() {
_image = [];
uploading = false;
postId = Uuid().v4();
});
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。