'How to set a new avatar in Flutter and display it using Firebase?
How to set a new avatar in Flutter and display it using Firebase ?
Solution 1:[1]
Setting an avatar: You could use FirebaseStorage to store user avatars. In order to do that I would setup an hierarchical storage structure like /users/{userID}/avatar.png whereas userID refers to be UID which Firebase assigned to the users. Uploading the image could be done with both the AdminSDK or using the ClientSDK for Firebase. You could setup a Firebase Rule to ensure each user can only update his own avatar image like this:
rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
match /users/{userId}/{allPaths=**} {
allow write: if (request.auth.uid == userId);
}
}
}
In order to upload the image you could procede as follows in your flutter app:
File avatarImgFile;
String fbUserId;
Future uploadImageToFirebase(BuildContext context) async {
String fileName = basename(avatarImgFile.path);
StorageReference firebaseStorageRef =
FirebaseStorage.instance.ref().child('users/$fbUserId/$fileName');
StorageUploadTask uploadTask = firebaseStorageRef.putFile(avatarImgFile);
StorageTaskSnapshot taskSnapshot = await uploadTask.onComplete;
taskSnapshot.ref.getDownloadURL().then(
(value) => print("Done: $value"),
);
}
Then you can use the obtained DownloadURL to display your image e.g. using CachedNetworkImage or similiar methods.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | finisinfinitatis |
