如何将图像上传到Firebase存储并自动存储在云Firestore中?

如何将图像上传到Firebase存储并自动存储在云Firestore中?,firebase,flutter,dart,google-cloud-firestore,Firebase,Flutter,Dart,Google Cloud Firestore,我目前正试图将图像上传到Firestore存储,并自动将图像URL存储到cloudfirestore。我已尝试手动将图像上载到Firebase存储,并将图像url粘贴到Cloud Firestore,然后检索图像以在我的应用程序中显示图像,效果良好。以下是我到目前为止所做的编码: models/enter.dart class Enter { final String enterId; final String enter; final String price; final

我目前正试图将图像上传到
Firestore存储
,并自动将图像
URL
存储到
cloudfirestore
。我已尝试手动将图像上载到
Firebase存储
,并将图像url粘贴到
Cloud Firestore
,然后检索图像以在我的应用程序中显示图像,效果良好。以下是我到目前为止所做的编码:

models/enter.dart


class Enter {

  final String enterId;
  final String enter;
  final String price;
  final String url;

  Enter({this.enter, this.price, @required this.enterId, this.url});

  factory Enter.fromJson(Map<String, dynamic> json){
    return Enter(
        enter: json['enter'],
        price: json['price'],
        url: json['url'],
        enterId: json['enterId']
    );
  }

  Map<String,dynamic> toMap(){
    return {
      'enter':enter,
      'price':price,
      'url':url,
      'enterId':enterId
    };
  }
}
import 'package:flutter/material.dart';
import 'package:journal_app/src/models/enter.dart';
import 'package:journal_app/src/services/firestore_service2.dart';
import 'package:uuid/uuid.dart';

class EnterProvider with ChangeNotifier {
  final firestoreService = FirestoreService2();
  String _enter;
  String _price;
  String _enterId;
  String _url;
  var uuid = Uuid();

  //Getters
  String get enter => _enter;
  String get price => _price;
  String get url => _url;
  Stream<List<Enter>> get enters => firestoreService.getEnter();

  //Setters
  set changeEnter(String enter){
    _enter = enter;
    notifyListeners();
  }

  set changePrice(String price){
    _price = price;
    notifyListeners();
  }

  set changeUrl(String url){
    _url = url;
    notifyListeners();
  }

  //Functions
  loadAll(Enter enter){
    if (enter != null && price != null){
      _enter =enter.enter;
      _price =enter.price;
      _url=enter.url;
      _enterId = enter.enterId;
    } else {
      _enter = null;
      _price = null;
      _url = null;
      _enterId = null;
    }
  }

  saveEnter(){
    if (_enterId == null){
      //Add
      var newEnter = Enter(enter: _enter, price: _price, url: _url, enterId: uuid.v1());
      print(newEnter.enter);
      print(newEnter.price);
      print(newEnter.url);
      firestoreService.setEnter(newEnter);
    } else {
      //Edit
      var updatedEnter = Enter(enter: _enter, price: _price, url: _url, enterId: _enterId);
      firestoreService.setEnter(updatedEnter);
    }
  }

  removeEnter(String enterId){
    firestoreService.removeEnter(enterId);
  }

}
provider/输入\u provider.dart


class Enter {

  final String enterId;
  final String enter;
  final String price;
  final String url;

  Enter({this.enter, this.price, @required this.enterId, this.url});

  factory Enter.fromJson(Map<String, dynamic> json){
    return Enter(
        enter: json['enter'],
        price: json['price'],
        url: json['url'],
        enterId: json['enterId']
    );
  }

  Map<String,dynamic> toMap(){
    return {
      'enter':enter,
      'price':price,
      'url':url,
      'enterId':enterId
    };
  }
}
import 'package:flutter/material.dart';
import 'package:journal_app/src/models/enter.dart';
import 'package:journal_app/src/services/firestore_service2.dart';
import 'package:uuid/uuid.dart';

class EnterProvider with ChangeNotifier {
  final firestoreService = FirestoreService2();
  String _enter;
  String _price;
  String _enterId;
  String _url;
  var uuid = Uuid();

  //Getters
  String get enter => _enter;
  String get price => _price;
  String get url => _url;
  Stream<List<Enter>> get enters => firestoreService.getEnter();

  //Setters
  set changeEnter(String enter){
    _enter = enter;
    notifyListeners();
  }

  set changePrice(String price){
    _price = price;
    notifyListeners();
  }

  set changeUrl(String url){
    _url = url;
    notifyListeners();
  }

  //Functions
  loadAll(Enter enter){
    if (enter != null && price != null){
      _enter =enter.enter;
      _price =enter.price;
      _url=enter.url;
      _enterId = enter.enterId;
    } else {
      _enter = null;
      _price = null;
      _url = null;
      _enterId = null;
    }
  }

  saveEnter(){
    if (_enterId == null){
      //Add
      var newEnter = Enter(enter: _enter, price: _price, url: _url, enterId: uuid.v1());
      print(newEnter.enter);
      print(newEnter.price);
      print(newEnter.url);
      firestoreService.setEnter(newEnter);
    } else {
      //Edit
      var updatedEnter = Enter(enter: _enter, price: _price, url: _url, enterId: _enterId);
      firestoreService.setEnter(updatedEnter);
    }
  }

  removeEnter(String enterId){
    firestoreService.removeEnter(enterId);
  }

}
屏幕/product.dart
此屏幕在listview中显示产品名称、价格和图像

import 'package:date_format/date_format.dart';
import 'package:flutter/material.dart';
import 'package:journal_app/src/models/enter.dart';
import 'package:journal_app/src/providers/enter_provider.dart';
import 'package:journal_app/src/screens/enter.dart';
import 'package:provider/provider.dart';

class ProductScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final enterProvider = Provider.of<EnterProvider>(context);
    return Scaffold(
      appBar: AppBar(
        title: Text('Products'),
      ),
      body: StreamBuilder<List<Enter>>(
          stream: enterProvider.enters,
          builder: (context, snapshot) {
            return ListView.builder(
                itemCount: snapshot.data.length,
                itemBuilder: (context, index) {
                  return ListTile(
                    leading: Image.network(
                      snapshot.data[index].url,
                      width: 100,
                      height: 100,
                      fit: BoxFit.fitWidth,
                    ),
                    trailing:
                    Icon(Icons.edit, color: Theme.of(context).accentColor),
                    title: Text(
                      snapshot.data[index].enter, style: TextStyle(fontSize: 25),
                    ),
                    subtitle: Text(
                      snapshot.data[index].price,
                    ),
                    onTap: () {
                      Navigator.of(context).push(MaterialPageRoute(
                          builder: (context) =>
                              EnterScreen(enter: snapshot.data[index], price: snapshot.data[index])));
                    },
                  );
                });
          }),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.add),
        onPressed: () {
          Navigator.of(context)
              .push(MaterialPageRoute(builder: (context) => EnterScreen()));
        },
      ),
    );
  }
}
import'package:date_format/date_format.dart';
进口“包装:颤振/材料.省道”;
导入“包:journal_app/src/models/enter.dart”;
导入“包:journal_app/src/providers/enter_provider.dart”;
导入“package:journal_app/src/screens/enter.dart”;
导入“包:provider/provider.dart”;
类ProductScreen扩展了无状态小部件{
@凌驾
小部件构建(构建上下文){
final enterProvider=Provider.of(上下文);
返回脚手架(
appBar:appBar(
标题:文本(“产品”),
),
正文:StreamBuilder(
流:enterProvider.enters,
生成器:(上下文,快照){
返回ListView.builder(
itemCount:snapshot.data.length,
itemBuilder:(上下文,索引){
返回列表块(
领先:Image.net(
snapshot.data[index].url,
宽度:100,
身高:100,
适合:BoxFit.fitWidth,
),
尾随:
图标(Icons.edit,颜色:Theme.of(context).accentColor),
标题:正文(
snapshot.data[index].输入,样式:TextStyle(fontSize:25),
),
字幕:文本(
快照.数据[索引].价格,
),
onTap:(){
导航器.of(上下文).push(MaterialPageRoute(
生成器:(上下文)=>
输入屏幕(输入:snapshot.data[index],价格:snapshot.data[index]);
},
);
});
}),
浮动操作按钮:浮动操作按钮(
子:图标(Icons.add),
已按下:(){
导航器(上下文)
.push(MaterialPage路由(生成器:(上下文)=>EnterScreen());
},
),
);
}
}
目标是
图像上载到
Firebase存储
,在
上载
新图像的同时存储
图像url


我需要这个项目的建议。

在你的情况下,你必须遵循以下步骤

  • 首先将您的图像上载到Firebase存储
  • ,然后获取下载的
    URL
  • 现在您有了下载
    URL
    ,您可以使用
    URL
    Enter
    对象上传到
    Cloud FireStore
  • 下面的方法显示了如何存储图像并获取下载url列表

    
    Future<String> uploadImage(var imageFile ) async {
        StorageReference ref = storage.ref().child("/photo.jpg");
        StorageUploadTask uploadTask = ref.putFile(imageFile);
        var dowurl = await (await uploadTask.onComplete).ref.getDownloadURL();
        url = dowurl.toString();
        return url; 
    }
    
    
    
    未来上载映像(var imageFile)异步{
    storagereferef=storage.ref().child(“/photo.jpg”);
    StorageUploadTask uploadTask=ref.putFile(imageFile);
    var dowurl=await(await uploadTask.onComplete);
    url=dowurl.toString();
    返回url;
    }
    
    要将图像上载到Firebase存储并保存在Cloud Firestore中,您需要执行以下操作:

    步骤1:获取要上载的图像 为此,您可以使用包 它将为您提供一个
    PickedFile
    对象(假设它是PickedFile)。使用以下代码将此对象转换为
    文件
    对象:

    final file = File(pickedFile.path);
    
    步骤2:将此文件上载到Firebase存储: 为要上载的图像指定一个唯一的名称

    final imageName = '${DateTime.now().millisecondsSinceEpoch}.png';
    
    创建Firebase存储引用:

    final firebaseStorageRef = FirebaseStorage.instance
            .ref()
            .child('images/$imageName'); // This will create a images directory in Firebase storage & save your image in that directory
    
    开始上载图像:

    final uploadTask = firebaseStorageRef.putFile(file);
    final taskSnapshot = await uploadTask.onComplete;
    
    获取图像URL:

    final _fileURL = await taskSnapshot.ref.getDownloadURL();
    
    在Cloud Firestore中保存此图像URL

    // This will save the image in "images" collection & update the "uploadedImage" value of document with id the same as the value of "id" variable. 
    await FirebaseFirestore.instance.collection(images).doc(id).update({'uploadedImage': _fileURL});
    

    如果要更新现有对象,请使用
    update
    方法,否则可以使用
    set
    方法。

    我之前做过这件事。在成功上传图像后存储图像文件时,您需要获取图像下载URL,然后您可以将图像
    URL
    保存到
    Cloud Firestore
    。就这样。