【发布时间】:2020-08-23 03:05:35
【问题描述】:
我正在用 Flutter 编写一个移动应用程序,并且遇到了与 Firebase 存储相关的问题。部分应用需要使用设备的摄像头拍照并将其上传到 Firebase Storage 存储桶。
上传功能一直有效,直到我在其他小改动中添加了一些身份验证功能。
问题来了:
Firebase 存储实例似乎未初始化。我已经看到一些例子表明 Firebase 可以使用一个函数来初始化,该函数接受 api 密钥、存储桶等参数。然而,谷歌文档从未提及此函数,而是建议将GoogleService-Info.plist 和google-services.json 复制到项目中。我已经这样做了,并且有效。我也在应用程序中使用的身份验证 api 和 Firestore 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 文件中与 Firebase 包含有关的部分。
# 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 实例是如何创建的。我将不胜感激有关此问题的任何指导。谢谢。
【问题讨论】:
-
你的 Firebase 存储规则是什么
-
@PeterHaddad
allow read, write是唯一的规则。
标签: firebase flutter firebase-authentication firebase-storage