dart – 如何在flutter图像选择器中将图像添加到firestore

dart – 如何在flutter图像选择器中将图像添加到firestore,第1张

概述我想将照片添加到firestore.你能告诉我怎么做吗? 我正在使用图像选择器在我的颤动应用程序中选择照片. 我的代码如下 import 'package:flutter/material.dart';import 'package:onlinecity/component/TextField/inputField.dart';import 'package:onlinecity/com 我想将照片添加到firestore.你能告诉我怎么做吗?

我正在使用图像选择器在我的颤动应用程序中选择照片.

我的代码如下

import 'package:Flutter/material.dart';import 'package:onlinecity/component/TextFIEld/inputFIEld.dart';import 'package:onlinecity/component/button/roundedbutton.dart';import 'package:onlinecity/component/button/textbutton.dart';import 'style.dart';import 'package:onlinecity/theme/style.dart';import 'package:Flutter/services.dart';import 'package:cloud_firestore/cloud_firestore.dart';import 'package:image_picker/image_picker.dart';import 'dart:async';import 'dart:io';class AddOfferScreen extends StatefulWidget {  @overrIDe  AddOfferScreenState createState() => new AddOfferScreenState();}class AddOfferScreenState extends State<AddOfferScreen> {  final GlobalKey<FormState> _formKey = new GlobalKey<FormState>();  final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();  bool _autovalIDate = false;  String _productTitle;  String _category;  String _contactNumber;  Future<file> _imagefile;  voID _onImagebuttonpressed(ImageSource source) {    setState(() {      _imagefile = ImagePicker.pickImage(source: source);    });  }  _onpressed() {    print("button clicked");  }  voID showInSnackbar(String value) {    _scaffoldKey.currentState        .showSnackbar(new Snackbar(content: new Text(value)));  }  bool _handlesubmitted() {    final FormState form = _formKey.currentState;    if (form.valIDate()) {      form.save();      return true;    }    return false;  }  voID valIDateAndsubmit() async{    if (_handlesubmitted()){      try {        Firestore.instance.collection('todos').document().setData({"productTitle":_productTitle,"category":_category,"contactNumber":_contactNumber});      }      catch (e){        print('Error: $e');      }    }  }  voID _showaddphoto(){    AlertDialog dialog = new AlertDialog(      actions: <Widget>[        new Iconbutton(icon: new Icon(Icons.camera_alt),onpressed: () => _onImagebuttonpressed(ImageSource.camera),tooltip: 'Take a Photo'),new Iconbutton(icon: new Icon(Icons.sd_storage),onpressed:  () => _onImagebuttonpressed(ImageSource.gallery),tooltip: 'Pick Image from gallery')      ],);    showDialog(context: context,child: dialog);  }  @overrIDe  Widget build(BuildContext context) {    // Todo: implement build    Size screenSize = Mediaquery.of(context).size;    //print(context.Widget.toString());    return new Scaffold(        key: _scaffoldKey,body: new SingleChildScrollVIEw(          child: new Container(            padding: new EdgeInsets.all(16.0),decoration: new Boxdecoration(image: backgroundImage),child: new Column(              mainAxisAlignment: MainAxisAlignment.end,crossAxisAlignment: CrossAxisAlignment.center,children: <Widget>[                new SizedBox(                    height: screenSize.height / 2 + 20,child: new Column(                      mainAxisAlignment: MainAxisAlignment.center,children: <Widget>[                        new Text(                          "CREATE ACCOUNT",textAlign: TextAlign.center,style: headingStyle,)                      ],)),new Column(                  children: <Widget>[                    new Form(                        key: _formKey,autovalIDate: _autovalIDate,//onWillPop: _warnUserAboutInvalIDData,child: new Column(                          children: <Widget>[                            new FutureBuilder<file>(                              future: _imagefile,builder: (BuildContext context,AsyncSnapshot<file> snapshot) {                                if (snapshot.connectionState == ConnectionState.done &&                                    snapshot.data != null) {                                  return new Image.file(snapshot.data);                                } else if (snapshot.error != null) {                                  return const Text('error picking image.');                                } else {                                  return const Text('You have not yet picked an image.');                                }                              },),new Raisedbutton.icon(onpressed: _showaddphoto,icon: new Icon(Icons.add_a_photo),label: new Text('Add Photo')),new inputFIEld(                              hintText: "product Title",obscureText: false,textinputType: TextinputType.text,textStyle: textStyle,textFIEldcolor: textFIEldcolor,icon: Icons.person_outline,iconcolor: colors.white,bottommargin: 20.0,valIDateFunction: (value)=> value.isEmpty ? 'Username can\'t be empty' : null,onSaved: (value)=> _productTitle = value,new inputFIEld(                              hintText: "category",textinputType: TextinputType.emailAddress,icon: Icons.mail_outline,valIDateFunction: (value)=> value.isEmpty ? 'Email can\'t be empty' : null,onSaved: (value)=> _category = value,new inputFIEld(                              hintText: "Contact Number",obscureText: true,icon: Icons.lock_open,bottommargin: 40.0,valIDateFunction: (value)=> value.isEmpty ? 'Contact number can\'t be empty' : null,onSaved:  (value)=> _contactNumber = value,new Roundedbutton(                                buttonname: "Continue",onTap: valIDateAndsubmit,wIDth: screenSize.wIDth,height: 50.0,bottommargin: 10.0,borderWIDth: 1.0)                          ],new Textbutton(                      buttonname: "Terms & Condition",onpressed: _onpressed,buttonTextStyle: buttonTextStyle,)                  ],)              ],));  }}
解决方法
import 'package:firebase_storage/firebase_storage.dart';  /////////        var filename = "filename.jpeg";  StorageUploadTask putfile =      storage.ref().child("folder/$filename").putfile(_image);  putfile.future.catchError(onError);  UploadTaskSnapshot uploadSnapshot = await putfile.future;  print("image uploaded");  Map<String,dynamic> pictureData = new Map<String,dynamic>();  pictureData["url"] = uploadSnapshot.downloadUrl.toString();  documentReference collectionReference =      Firestore.instance.collection("collection").document(filename);  await Firestore.instance.runTransaction((transaction) async {    await transaction.set(collectionReference,pictureData);    print("instance created");  }).catchError(onError);

在这里,这会将文件存储到存储中,然后将downloadUrl保存到您的集合中.而不是文档(filename),您可以选择自己的文档ID.

总结

以上是内存溢出为你收集整理的dart – 如何在flutter图像选择器中将图像添加到firestore全部内容,希望文章能够帮你解决dart – 如何在flutter图像选择器中将图像添加到firestore所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1000527.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-21
下一篇 2022-05-21

发表评论

登录后才能评论

评论列表(0条)

保存