![](/img/trans.png)
[英]How to load image into memory and then save to Firebase Storage in Flutter / Dart
[英]Upload and save image into firebase Storage flutter dart
我正在嘗試上傳圖片並將用戶信息注冊到 firebase 存儲和 Firestore 問題是由於某種原因它不接受此代碼,它說我需要輸入;
_registerUser()
之后是我用來保存和上傳信息的代碼:
Future<void> uploadAndSaveImage() async {
if (_imageFile != null) {
_passwordTextEditingController.text ==
_cPasswordTextEditingController.text
? _emailTextEditingController.text.isNotEmpty &&
_passwordTextEditingController.text.isNotEmpty &&
_cPasswordTextEditingController.text.isNotEmpty &&
_nameTextEditingController.text.isNotEmpty
?uploadToStorage() , _registerUser()
: displayDialog("Please fill up the registration complete form..")
: displayDialog("Password do not match.");
} else {
showDialog(
context: context,
builder: ((c) {
return ErrorAlertDialog(
message: "Please select an image.",
);
}));
}
}
注冊用戶 function:
FirebaseAuth _auth = FirebaseAuth.instance;
void _registerUser() async { FirebaseUser firebaseUser;
await _auth
.createUserWithEmailAndPassword(
email: _emailTextEditingController.text.trim(),
password: _passwordTextEditingController.text.trim(),
)
.then((auth) {
firebaseUser = auth.user;
}).catchError((error) {
Navigator.pop(context);
showDialog(
context: context,
builder: (c) {
return ErrorAlertDialog(
message: error.message.toString(),
);
});
});
if (firebaseUser != null) {
saveUserInfoToFireStore(firebaseUser).then((value) {
Navigator.pop(context);
Route route = MaterialPageRoute(builder: (c) => StoreHome());
Navigator.pushReplacement(context, route);
});
}
}
Ps:我還是新手,這是我使用 flutter 的第三個應用程序
我已使用此代碼將用戶圖像從本地存儲上傳到 Firebase,並使用uid
作為參考名稱。
final _firebaseAuth = FirebaseAuth.instance;
FirebaseStorage firebaseStorage = FirebaseStorage.instance;
FirebaseFirestore firebaseFirestore = FirebaseFirestore.instance;
final imgPicker = ImagePicker();
File image;
String photoUrl = "";
bool _uploading = false;
uploadPic() async {
try {
setState(() {
_uploading = true;
});
// picking Image from local storage
final file = await imgPicker.getImage(
source: ImageSource.gallery,
);
if (file != null) {
image = File(file.path);
} else {
setState(() {
_uploading = false;
});
}
// creating ref at Firebase Storage with userID
Reference ref =
firebaseStorage.ref(_firebaseAuth.currentUser.uid).child("dp");
ref.putFile(image).whenComplete(() {
print("Pic Uploaded Successfully!");
setState(() {
_uploading = false;
});
// refreshing the UI when photo updated
getUploadedPic();
});
} catch (e) {
print(e);
}
}
上傳后您可能會得到圖像 URL 如下:
getUploadedPic() async {
// getting dp URL link
photoUrl = await firebaseStorage
.ref("${_firebaseAuth.currentUser.uid}/dp")
.getDownloadURL()
.whenComplete(() => print("URL UPLOADED AT: $photoUrl"));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.