无法从Firebase存储中的上传图像获取.getDownloadURL()

时间:2020-06-15 08:22:35

标签: flutter dart google-cloud-firestore firebase-storage flutter-dependencies

要在Cloud Firestore中创建配置文件信息,我尝试使用 NonExistingProfileForm

照片是从画廊中选择的,并上传到了Firebase存储中,但我似乎无法获取它的URL。 我无法将URL分配给 _imageUrl ,并且文档中有一个空值。

here's the image of firestore document with 'profilePic' key with empty value.

这是代码。

import 'package:comcrop/shared/shared.dart';
import 'package:comcrop/models/users.dart';
import 'package:comcrop/services/database.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:provider/provider.dart';
import 'dart:io';

class NonExistingProfileForm extends StatefulWidget {
  @override
  _NonExistingProfileFormState createState() => _NonExistingProfileFormState();
}

class _NonExistingProfileFormState extends State<NonExistingProfileForm> {
  final _formKey = GlobalKey<FormState>();

  // form values
  String netimg =
      'https://www.psychowave.org/wp-content/uploads/2015/06/cd1-960x960.jpg';

  String _firstName;
  String _lastName;
  String _phoneNumber;
  String _address;
  String _imageUrl;
  File _image;

  @override
  Widget build(BuildContext context) {
    final user = Provider.of<User>(context);

    Future getImage() async {
      var image = await ImagePicker.pickImage(source: ImageSource.gallery);

      setState(() {
        _image = image;
      });
    }

    Future uploadPic(BuildContext context) async {
      StorageReference ref =
          FirebaseStorage.instance.ref().child(user.uid);
      StorageUploadTask task = ref.putFile(_image);

      if (task.isComplete) {
        setState(() {
          _imageUrl = ref.getDownloadURL() as String;
          print(_imageUrl);
        });
      }
    }

    return Form(
      key: _formKey,
      child: SingleChildScrollView(
        child: Column(
          children: <Widget>[
            Text('add profile',
                style: Theme.of(context).appBarTheme.textTheme.headline6),
            SizedBox(height: 20.0),
            Row(
              children: [
                CircleAvatar(
                  radius: 50,
                  backgroundImage: (_image != null)
                      ? FileImage(
                          _image,
                        )
                      : NetworkImage(netimg),
                ),
                SizedBox(width: 50),
                FlatButton.icon(
                  onPressed: () => getImage(),
                  icon: Icon(
                    Icons.camera,
                    color: Colors.white,
                  ),
                  label: Text('image',
                      style: Theme.of(context).textTheme.bodyText2),
                ),
              ],
            ),
            SizedBox(height: 50),
            TextFormField(
              style: Theme.of(context).textTheme.bodyText2,
              initialValue: '',
              decoration: textInputDecoration.copyWith(labelText: 'first name'),
              validator: (val) =>
                  val.isEmpty ? 'Please enter first name' : null,
              onChanged: (val) => setState(() => _firstName = val),
            ),
            SizedBox(height: 20.0),
            TextFormField(
              style: Theme.of(context).textTheme.bodyText2,
              initialValue: '',
              decoration: textInputDecoration.copyWith(labelText: 'last name'),
              validator: (val) => val.isEmpty ? 'Please enter last name' : null,
              onChanged: (val) => setState(() => _lastName = val),
            ),
            SizedBox(height: 20.0),
            TextFormField(
              style: Theme.of(context).textTheme.bodyText2,
              initialValue: '',
              decoration:
                  textInputDecoration.copyWith(labelText: 'phone number'),
              validator: (val) =>
                  val.length != 10 ? 'Please enter phone number' : null,
              onChanged: (val) => setState(() => _phoneNumber = val),
            ),
            SizedBox(height: 30.0),
            TextFormField(
              maxLines: 4,
              style: Theme.of(context).textTheme.bodyText2,
              initialValue: '',
              decoration:
                  textInputDecoration.copyWith(labelText: 'genaral address'),
              validator: (val) =>
                  val.isEmpty ? 'Please enter genaral address' : null,
              onChanged: (val) => setState(() => _address = val),
            ),
            SizedBox(height: 20.0),
            SizedBox(
              height: MediaQuery.of(context).viewInsets.bottom,
            ),
            RaisedButton(
                child:
                    Text('update', style: Theme.of(context).textTheme.button),
                onPressed: () async {
                  uploadPic(context);
                  if (_formKey.currentState.validate()) {
                    await DatabaseService(uid: user.uid).updateUserData(
                      _firstName,
                      _lastName,
                      int.parse(_phoneNumber),
                      _address,
                      _imageUrl,
                    );
                    Navigator.pop(context);
                  }
                }),
          ],
        ),
      ),
    );
  }
}

我检查了存储空间,并在那儿找到了上传的图片,但是我似乎无法获得的不是URL。 我该如何实现?

2 个答案:

答案 0 :(得分:1)

尝试等待:

await uploadPic(context);

尝试使用此:-

await (await task.onComplete).ref.getDownloadURL()

希望获得帮助:)

答案 1 :(得分:0)

您可能需要等待task.onComplete尝试以下操作:

 Future uploadPic(BuildContext context) async {
    try {
      StorageReference ref =
          FirebaseStorage.instance.ref().child(user.uid);
      StorageUploadTask task = ref.putFile(_image);

      await task.onComplete;
      final fileURL = await ref.getDownloadURL() as String; 


      setState(() {
        _imageUrl = fileURL;
      }); 
      print(_imageUrl);
    } catch (error) {
      // check in debugger or print error!
    }

}