Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set Bytes data in firebase using flutter?

The Cloud FireStore supports Bytes datatype, but failed to give an example of how to setting it, i am trying to upload a thumbnail image as bytes to the FireStore, in Flutter. Can someone give an example how to do it?

File imageFile;
final databaseReference = Firestore.instance;
    await databaseReference
        .collection("Users")
        .document('${user.strId}')
        .setData({'thumbnailPhoto': ???}); // how to convert imageFile to Bytes?

EDIT I think both of the answers posted by Richard Heap and Jay Vasan work, using blob or base64Encode actually give the same value in FireStore under key thumbnailPhoto. I decide to give the bounty to Richard since it hides the details of the internal binary coding.

like image 225
Allanqunzi Avatar asked Oct 19 '19 22:10

Allanqunzi


2 Answers

Cloud Firestore raw bytes is represented by Blob in Dart, so use:

    .setData({'thumbnailPhoto', Blob(await file.readAsBytes())});

When you read this back from Cloud Firestore you'll get back a Blob. Access its bytes with blob.bytes. For example, to write to a file use:

  await file.writeAsBytes(theBlob.bytes); // overwrite or create the file
like image 133
Richard Heap Avatar answered Oct 24 '22 08:10

Richard Heap


In this case, you can convert the image to base64 string.

open image as:

var imageFile = File(imagePath);

convert to base64:

String base64Image = base64Encode(imageFile.readAsBytesSync());
like image 39
alter123 Avatar answered Oct 24 '22 08:10

alter123