How do I read and write a text file from firebase storage in Flutter?

Viewed 1817

I need to make a storage for my saved images in firebase storage. Is there a way I can read and write to online text file on firebase storage in flutter? Is there any alternative to make my images storage?

1 Answers

It's so simple. Let's explain the solution with the example.

import the library as following :

import package:firebase_storage/firebase_storage.dart' as firebase_storage;

Secondly, get the firebase reference by :

firebase_storage.Reference ref = firebase_storage.FirebaseStorage.instance
.ref() 
.child('playground')
.child('/put-string-example.txt');

Third, to get the data from the current file you are in :

Uint8List downloadedData  =  await ref.getData();

Fourth, now you will get a value in Uint8List format, you have to decode this value by Utf8Codec class that is an instance of the default implementation of the [Utf8Codec] and you will get the result in String object:

print(utf8.decode(downloadedData)); 

Now for writing it's a bit easier : Firstly, we have the String object :

String putStringText = 'Hello World';

Secondly, we write to the current file with firebase ref object :

ref.putString(putStringText,
metadata: firebase_storage.SettableMetadata(
contentLanguage: 'en'));

the first argument is our string the second one is the metadata that allows you some extra options like the contentLanguage param.

I hope you find it useful.

Related