我正在用Flutter编写一个移动应用程序,遇到了一个与Firebase存储相关的问题。应用程序的一部分需要用设备的摄像头拍照并上传到Firebase存储桶中。
上载功能一直有效,直到我在其他小更改中添加了一些身份验证功能。
以下是问题所在:
Firebase存储实例似乎未初始化。我见过一些例子,显示Firebase可以用一个接受api密钥、存储桶等参数的函数进行初始化。然而,谷歌文档从来没有提到这个函数,而是建议将GoogleService-Info.plist
和google-services.json
复制到项目中。我已经这样做了,并且它起作用了。身份验证api和Firestore api,我也在应用程序中使用这两个api,都可以正常工作。这只是Firebase存储有问题。
例如,在我的main函数中,我添加了以下代码来显示问题。
Future<void> main() async{
// setup camera
WidgetsFlutterBinding.ensureInitialized();
final cameras = await availableCameras();
// look here!!
print('firestore: ${Firestore.instance.app}');
print('storage: ${FirebaseStorage.instance.app}');
runApp(MyApp(cameras: cameras));
}
在运行应用程序(在物理设备上)时,控制台输出如下:
Restarted application in 1,097ms.
flutter: firestore: FirebaseApp(__FIRAPP_DEFAULT)
flutter: storage: null
我真的很难理解是什么原因导致Firebase的部分初始化失败。我尝试在Firebase控制台中更改访问规则,但没有效果。下面我粘贴了我的pubspec.yaml
文件的do with Firebase includes部分。
# Firebase
firebase_core: ^0.4.0+9
firebase_analytics: ^5.0.2
firebase_auth: ^0.14.0+5
cloud_firestore: ^0.12.9+5
firebase_storage: ^3.0.8
此外,下面是向Storage API发出请求的代码。同样,我不认为这是问题所在,因为实例从一开始就是空的,但这里是为了完整性:
// saves a locally stored image at local_uri as name. After the storage task
// is complete, the DocumentReference ref is updated with the new url
Future<void> _save_storage(String name, String local_uri, DocumentReference ref) async {
StorageReference storage_reference;
storage_reference = FirebaseStorage.instance.ref().child('images/$name');
final StorageUploadTask upload_task = storage_reference.putFile(io.File(local_uri));
final StorageTaskSnapshot download_url = (await upload_task.onComplete);
final String url = (await download_url.ref.getDownloadURL());
// now, update the file in the database to point to the correct storage
// url
Firestore.instance.runTransaction((transaction) async {
await transaction.update(ref, {'image_url' : url});
});
}
令人沮丧的是,这个问题没有抛出异常。文件根本不会上传到存储桶中。我知道实例字段是通过在调试模式下执行一些随机探测来取消初始化的。此外,我还发现上面的StorageUploadTask实例的错误代码为-13000,但是我在任何地方都没有找到任何关于此错误代码的文档。
我对Flutter和Firebase都是新手,所以我认为这里的部分问题是我不理解Firebase实例是如何创建的。在这个问题上如果有任何指导我将不胜感激。谢谢。
发布于 2020-05-07 23:15:31
解决了!我有一个与Firebase存储一起运行的缓存,它允许在上载发生时重命名文件。现在,重命名任务被阻塞,直到上传完成。我仍然不确定为什么Firebase存储实例没有使用我期望的数据进行初始化,但既然它现在正在工作,我愿意忽略这一点。
https://stackoverflow.com/questions/61664221
复制相似问题