【问题标题】:how can i save photo to firebase storage and send the url link to cloud firestore?如何将照片保存到 Firebase 存储并将 URL 链接发送到 Cloud Firestore?
【发布时间】:2018-11-06 00:43:11
【问题描述】:

如何将照片保存到 firebase 存储并将 url 链接发送到 cloud 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:io';
import 'package:firebase_storage/firebase_storage.dart';
import 'dart:async';

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;
  FirebaseStorage storage;

  String _path;
  File _cachedFile;
  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",
                              obscureText: false,
                              textInputType: TextInputType.emailAddress,
                              textStyle: textStyle,
                              textFieldColor: textFieldColor,
                              icon: Icons.mail_outline,
                              iconColor: Colors.white,
                              bottomMargin: 20.0,
                              validateFunction: (value)=> value.isEmpty ? 'Email can\'t be empty' : null,
                              onSaved: (value)=> _category = value,
                            ),
                            new InputField(
                              hintText: "Contact Number",
                              obscureText: true,
                              textInputType: TextInputType.text,
                              textStyle: textStyle,
                              textFieldColor: textFieldColor,
                              icon: Icons.lock_open,
                              iconColor: Colors.white,
                              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,)
                  ],
                )
              ],
            ),
          ),
        ));
  }
}

【问题讨论】:

    标签: firebase dart flutter firebase-storage


    【解决方案1】:

    这是一个代码 sn-p。当你有来自ImagePickerFile 时,你应该运行它。

    图像选择器:请注意 setState 不能是异步的,因此您需要在外部等待并在 setState 中将局部变量传递给字段。

      void _onImageButtonPressed(ImageSource source) async {
      File image = await ImagePicker.pickImage(source: source);
        setState(() {
          _imageFile = image;
        });
    
      }
    

    这个sn-p你要上传的时候需要调用

      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);
    

    【讨论】:

    • 我用 ///////// void _onImageButtonPressed(ImageSource source) { setState(() { _imageFile = ImagePicker.pickImage(source: source); }); }
    • 里面有图片选择器
    • 哈哈好,那你需要选择是选择图片后自动上传,还是做一个按钮来运行代码的恢复。 _imageFile 是您需要调用 putFile
    • 我可以改变 Future _imageFile;到文件_imageFile;因为在此更改之前,它向我显示了等待中的错误 ....................但是在更改后,onError 上显示的另一个错误是未定义的名称 onError ..我为此导入了什么
    • 这里,查看答案顶部
    猜你喜欢
    • 2021-06-30
    • 2021-03-14
    • 2021-10-01
    • 2021-03-13
    • 2019-11-15
    • 2017-06-16
    • 2021-05-01
    • 2019-04-18
    • 2021-10-14
    相关资源
    最近更新 更多