我如何从Firestore中的Firebase存储中获取URL

我如何从Firestore中的Firebase存储中获取URL,firebase,flutter,google-cloud-firestore,Firebase,Flutter,Google Cloud Firestore,我想将图像上载到firebase存储中,以将下载URL存储在firestore中。我有我吼叫过的密码!但问题是,每当我尝试上传图像时,图像上传成功,但URL没有保存在firestore中。它返回空值 如何将URL存储到firestore class NewFund extends StatefulWidget { NewFund(); @override _NewFundState createState() => _NewFundState(); } class

我想将图像上载到firebase存储中,以将下载URL存储在firestore中。我有我吼叫过的密码!但问题是,每当我尝试上传图像时,图像上传成功,但URL没有保存在firestore中。它返回空值

如何将URL存储到firestore

    class NewFund extends StatefulWidget {
  NewFund();

  @override
  _NewFundState createState() => _NewFundState();
}

class _NewFundState extends State<NewFund> {
  final GlobalKey<FormState> _fundFormKey = GlobalKey<FormState>();

  String userID, postName, postDetails, postImgUrl;
  String filepath = '${DateTime.now()}.png';
  File _imageFile;
  StorageUploadTask _uploadTask;

  final FirebaseStorage _storage =
      FirebaseStorage(storageBucket: 'gs://i-donate-402dd.appspot.com');

  getUserName(userId) {
    this.userID = userID;
  }

  getPostName(postName) {
    this.postName = postName;
  }

  getTaskDetails(postDetails) {
    this.postDetails = postDetails;
  }

  getImageUrl(postImgUrl) {
    this.postImgUrl = postImgUrl;
  }

  int _myPostType = 0;
  String postVal;

  void _handleTaskType(int value) {
    setState(() {
      _myPostType = value;
      switch (_myPostType) {
        case 1:
          postVal = 'food';
          break;
        case 2:
          postVal = 'health';
          break;
        case 3:
          postVal = 'money';
          break;
        case 4:
          postVal = 'clothes';
          break;
        case 5:
          postVal = 'education';
          break;
      }
    });
  }

  Widget radioButton(bool isSelected) => Container(
        width: 16.0,
        height: 16.0,
        padding: EdgeInsets.all(2.0),
        decoration: BoxDecoration(
            shape: BoxShape.circle,
            border: Border.all(width: 2.0, color: Colors.black)),
        child: isSelected
            ? Container(
                width: double.infinity,
                height: double.infinity,
                decoration:
                    BoxDecoration(shape: BoxShape.circle, color: Colors.black),
              )
            : Container(),
      );

  Widget horizontalLine() => Padding(
        padding: EdgeInsets.symmetric(horizontal: 16.0),
        child: Container(
          width: ScreenUtil.getInstance().setWidth(120),
          height: 1.0,
          color: Colors.black26.withOpacity(.2),
        ),
      );

  createFund() {
    var authP = Provider.of<AuthP>(context);
    var uid = authP.uid;
    DocumentReference ds =
        Firestore.instance.collection('posts').document(postName);
    Map<String, dynamic> posts = {
      "userID": uid,
      "postName": postName,
      "postDetails": postDetails,
      "postCat": postVal,
      "postImgUrl": postImgUrl,
    };
    setState(() {
      _saveImage();
    });

    ds.setData(posts).whenComplete(() {
      print("posts updated");
    });
  }




  Future<String> _saveImage() async {
    _uploadTask = _storage.ref().child(filepath).putFile(_imageFile);
    var downURL = await (await _uploadTask.onComplete).ref.getDownloadURL();
    postImgUrl = downURL.toString();
    print('LINK URL : $postImgUrl');
    return postImgUrl;
  }

  Future<void> _pickImage(ImageSource source) async {
    File selected = await ImagePicker.pickImage(source: source);
    setState(() {
      _imageFile = selected;
    });
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.instance = ScreenUtil.getInstance()..init(context);
    ScreenUtil.instance =
        ScreenUtil(width: 750, height: 1334, allowFontScaling: true);
    return Form(
      key: _fundFormKey,
      child: Scaffold(
        backgroundColor: Colors.white,
        resizeToAvoidBottomPadding: true,
        body: Stack(
          fit: StackFit.expand,
          children: <Widget>[
            Column(
              crossAxisAlignment: CrossAxisAlignment.end,
              children: <Widget>[
                Padding(
                  padding: EdgeInsets.only(top: 20.0),
                  child: Image.asset("assets/imagemain.jpg"),
                ),
                Expanded(
                  child: Container(),
                ),
                Image.asset("assets/image_02.png")
              ],
            ),
            SingleChildScrollView(
              child: Padding(
                padding: EdgeInsets.only(left: 28.0, right: 28.0, top: 60.0),
                child: Column(
                  children: <Widget>[
                    SizedBox(
                      height: ScreenUtil.getInstance().setHeight(20),
                    ),
                    Container(
                      width: double.infinity,
                      height: ScreenUtil.getInstance().setHeight(850),
                      decoration: BoxDecoration(
                          color: Colors.white,
                          borderRadius: BorderRadius.circular(8.0),
                          boxShadow: [
                            BoxShadow(
                                color: Colors.black12,
                                offset: Offset(0.0, 15.0),
                                blurRadius: 15.0),
                            BoxShadow(
                                color: Colors.black12,
                                offset: Offset(0.0, -10.0),
                                blurRadius: 10.0),
                          ]),
                      child: Padding(
                        padding:
                            EdgeInsets.only(left: 16.0, right: 16.0, top: 16.0),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: <Widget>[
                            Text("Raise Fund",
                                style: TextStyle(
                                    fontSize:
                                        ScreenUtil.getInstance().setSp(45),
                                    fontFamily: "Poppins-Bold",
                                    letterSpacing: .6)),
                            SizedBox(
                              height: ScreenUtil.getInstance().setHeight(30),
                            ),
                            Text("Title",
                                style: TextStyle(
                                    fontFamily: "Poppins-Medium",
                                    fontSize:
                                        ScreenUtil.getInstance().setSp(26))),
                            TextField(
                              keyboardType: TextInputType.multiline,
                              maxLines: null,
                              decoration: InputDecoration(),
                              onChanged: (String name) {
                                getPostName(name);
                              },
                            ),
                            SizedBox(
                              height: ScreenUtil.getInstance().setHeight(30),
                            ),
                            Text("Fund Details",
                                style: TextStyle(
                                    fontFamily: "Poppins-Medium",
                                    fontSize:
                                        ScreenUtil.getInstance().setSp(26))),
                            TextField(
                              keyboardType: TextInputType.multiline,
                              maxLines: null,
                              decoration: InputDecoration(),
                              onChanged: (String postDetails) {
                                getTaskDetails(postDetails);
                              },
                            ),
                            SizedBox(
                              height: ScreenUtil.getInstance().setHeight(30),
                            ),
                            Text("Select Fund Type",
                                style: TextStyle(
                                    fontFamily: "Poppins-Bold",
                                    fontSize:
                                        ScreenUtil.getInstance().setSp(26))),
                            SizedBox(
                              height: ScreenUtil.getInstance().setHeight(30),
                            ),
                            Column(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: <Widget>[
                                Row(
                                  mainAxisAlignment: MainAxisAlignment.start,
                                  children: <Widget>[
                                    Radio(
                                      value: 1,
                                      groupValue: _myPostType,
                                      onChanged: _handleTaskType,
                                      activeColor: Color(0xff4158ba),
                                    ),
                                    Text(
                                      'Food',
                                      style: TextStyle(fontSize: 16.0),
                                    ),
                                  ],
                                ),
                                Row(
                                  mainAxisAlignment: MainAxisAlignment.start,
                                  children: <Widget>[
                                    Radio(
                                      value: 2,
                                      groupValue: _myPostType,
                                      onChanged: _handleTaskType,
                                      activeColor: Color(0xfffb537f),
                                    ),
                                    Text(
                                      'Health',
                                      style: TextStyle(
                                        fontSize: 16.0,
                                      ),
                                    ),
                                  ],
                                ),
                                Row(
                                  mainAxisAlignment: MainAxisAlignment.start,
                                  children: <Widget>[
                                    Radio(
                                      value: 3,
                                      groupValue: _myPostType,
                                      onChanged: _handleTaskType,
                                      activeColor: Color(0xff4caf50),
                                    ),
                                    Text(
                                      'Money',
                                      style: TextStyle(fontSize: 16.0),
                                    ),
                                  ],
                                ),
                                Row(
                                  mainAxisAlignment: MainAxisAlignment.start,
                                  children: <Widget>[
                                    Radio(
                                      value: 4,
                                      groupValue: _myPostType,
                                      onChanged: _handleTaskType,
                                      activeColor: Color(0xff9962d0),
                                    ),
                                    Text(
                                      'Clothes',
                                      style: TextStyle(fontSize: 16.0),
                                    ),
                                  ],
                                ),
                                Row(
                                  mainAxisAlignment: MainAxisAlignment.start,
                                  children: <Widget>[
                                    Radio(
                                      value: 5,
                                      groupValue: _myPostType,
                                      onChanged: _handleTaskType,
                                      activeColor: Color(0xff0dc8f5),
                                    ),
                                    Text(
                                      'Education',
                                      style: TextStyle(fontSize: 16.0),
                                    ),
                                  ],
                                ),
                              ],
                            ),
                          ],
                        ),
                      ),
                    ),
                    SizedBox(
                      height: ScreenUtil.getInstance().setHeight(20),
                    ),
                    RaisedButton(
                      onPressed: () {
                        _pickImage(ImageSource.gallery);
                      },
                      child: Text('Upload Document'),
                    ),
                    SizedBox(
                      height: ScreenUtil.getInstance().setHeight(20),
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: <Widget>[
                        InkWell(
                          child: Container(
                            width: ScreenUtil.getInstance().setWidth(330),
                            height: ScreenUtil.getInstance().setHeight(100),
                            decoration: BoxDecoration(
                                gradient: LinearGradient(colors: [
                                  Color(0xFF17ead9),
                                  Color(0xFF6078ea)
                                ]),
                                borderRadius: BorderRadius.circular(6.0),
                                boxShadow: [
                                  BoxShadow(
                                      color: Color(0xFF6078ea).withOpacity(.3),
                                      offset: Offset(0.0, 8.0),
                                      blurRadius: 8.0)
                                ]),
                            child: Material(
                              color: Colors.transparent,
                              child: InkWell(
                                onTap: () {
                                  createFund();
                                },
                                child: Center(
                                  child: Text("Raise",
                                      style: TextStyle(
                                          color: Colors.white,
                                          fontFamily: "Poppins-Bold",
                                          fontSize: 18,
                                          letterSpacing: 1.0)),
                                ),
                              ),
                            ),
                          ),
                        )
                      ],
                    ),
                  ],
                ),
              ),
            )
          ],
        ),
      ),
    );
  }
}
class NewFund扩展StatefulWidget{
新基金();
@凌驾
_NewFundState createState()=>\u NewFundState();
}
类_NewFundState扩展状态{
最终GlobalKey _fundFormKey=GlobalKey();
字符串userID、postName、postDetails、postMgURL;
字符串文件路径=“${DateTime.now()}.png”;
文件imageFile;
StorageUploadTask\u uploadTask;
最终FirebaseStorage\u存储=
FirebaseStorage(storageBucket:'gs://i-denate-402dd.appspot.com');
getUserName(用户ID){
this.userID=userID;
}
getPostName(postName){
this.postName=postName;
}
获取详细信息(postDetails){
this.postDetails=postDetails;
}
getImageUrl(postImgUrl){
this.postImgUrl=postImgUrl;
}
int_myPostType=0;
字符串后置;
void _handleTaskType(int值){
设置状态(){
_myPostType=值;
开关(_myPostType){
案例1:
postVal=‘食物’;
打破
案例2:
postVal='健康';
打破
案例3:
postVal=‘货币’;
打破
案例4:
postVal=‘衣服’;
打破
案例5:
postVal=‘教育’;
打破
}
});
}
Widget单选按钮(bool isSelected)=>容器(
宽度:16.0,
身高:16.0,
填充:所有边缘设置(2.0),
装饰:盒子装饰(
形状:BoxShape.circle,
边框:border.all(宽度:2.0,颜色:Colors.black)),
孩子:我当选了
?容器(
宽度:double.infinity,
高度:双无限,
装饰:
盒子装饰(形状:盒子形状。圆圈,颜色:颜色。黑色),
)
:Container(),
);
Widget horizontalLine()=>填充(
填充:边缘组。对称(水平:16.0),
子:容器(
宽度:ScreenUtil.getInstance().setWidth(120),
高度:1.0,
颜色:颜色。黑色26。不透明度(.2),
),
);
createFund(){
var authP=Provider.of(上下文);
var uid=authP.uid;
文件参考=
Firestore.instance.collection('posts').document(postName);
地图柱={
“userID”:uid,
“postName”:postName,
“postDetails”:postDetails,
“Postat”:postVal,
“postImgUrl”:postImgUrl,
};
设置状态(){
_saveImage();
});
ds.setData(posts).whenComplete(){
打印(“更新帖子”);
});
}
Future\u saveImage()异步{
_uploadTask=\u storage.ref().child(filepath).putFile(\u imageFile);
var downURL=await(await _uploadTask.onComplete);
postImgUrl=downURL.toString();
打印('linkurl:$postImgUrl');
返回postImgUrl;
}
Future\u pickImage(ImageSource)异步{
所选文件=等待ImagePicker.pickImage(源:源);
设置状态(){
_imageFile=已选择;
});
}
@凌驾
小部件构建(构建上下文){
ScreenUtil.instance=ScreenUtil.getInstance()…初始化(上下文);
ScreenUtil.instance=
ScreenUtil(宽度:750,高度:1334,allowFontScaling:true);
报税表(
密钥:_fundFormKey,
孩子:脚手架(
背景颜色:Colors.white,
resizeToAvoidBottomPadding:true,
主体:堆栈(
fit:StackFit.expand,
儿童:[
纵队(
crossAxisAlignment:crossAxisAlignment.end,
儿童:[
填充物(
填充:仅限边缘设置(顶部:20.0),
子项:Image.asset(“assets/imagemain.jpg”),
),
扩大(
子级:容器(),
),
Image.asset(“assets/Image\u 02.png”)
],
),
SingleChildScrollView(
孩子:填充(
填充:仅限边缘设置(左:28.0,右:28.0,顶部:60.0),
子:列(
儿童:[
大小盒子(
高度:ScreenUtil.getInstance().setHeight(20),
),
容器(
宽度:double.infinity,
高度:ScreenUtil.getInstance().setHeight(850),
装饰:盒子装饰(
颜色:颜色,白色,
边界半径:边界半径。圆形(8.0),
boxShadow:[
箱形阴影(
颜色:颜色。黑色,
偏移量:偏移量(0.0,15.0),
半径:15.0),
箱形阴影(
颜色:颜色。黑色,
偏移量:偏移量(0.0,-10.0),
半径:10.0),
]),
孩子:填充(
衬垫:
仅限边集(左:16.0,右:16.0,顶:16.0),
子:列(
crossAxisAlignment:crossAxisAlignment.start,
儿童:[
文本(“筹集资金”,
样式:TextStyle(
字体大小:
ScreenUtil.getInstance().setSp(45),
fontFamily:“波平斯黑体”,
字母间距:.6),
          final StorageReference storageReference =
                FirebaseStorage.instance.ref().child('images/$name');
            StorageUploadTask uploadTask = storageReference.putData(asset);

            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.
     });
         await uploadTask.onComplete;
            streamSubscription.cancel();
//get your ref url    

            String docUrl = await (await uploadTask.onComplete).ref.getDownloadURL();
//docUrl is your url as a string
            Firestore.instance
                .collection('collectiion')
                .document()
        .updateData({"url": docUrl});