Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dart / flutter: download or read the contents of a Google Drive file

I have a public (anyone with the link can view) file on my Google Drive and I want to use the content of it in my Android app.

From what I could gather so far, I need the fileID, the OAuth token and the client ID - these I already got. But I can't figure out what is the exact methodology of authorising the app or fetching the file.

EDIT:

Simply reading it using file.readAsLines didn't work:

final file = new File(dogListTxt);
  Future<List<String>> dogLinks = file.readAsLines();

  return dogLinks;

The dogLinks variable isn't filled with any data, but I get no error messages.

The other method I tried was following this example but this is a web based application with explicit authorization request (and for some reason I was never able to import the dart:html library).

The best solution would be if it could be done seamlessly, as I would store the content in a List at the application launch, and re-read on manual refresh button press.

I found several old solutions here, but the methods described in those doesn't seem to work anymore (from 4-5 years ago).

Is there a good step-by-step tutorial about integrating the Drive API in a flutter application written in dart?

like image 728
Zoltán Györkei Avatar asked Apr 04 '18 05:04

Zoltán Györkei


1 Answers

I had quite a bit of trouble with this, it seems much harder than it should be. Also this is for TXT files only. You need to use files.export() for other files.

First you need to get a list fo files.

ga.FileList textFileList = await drive.files.list(q: "'root' in parents");

Then you need to get those files based on ID (This is for TXT Files)

ga.Media response = await drive.files.get(filedId, downloadOptions: ga.DownloadOptions.FullMedia);

Next is the messy part, you need to convert your Media object stream into a File and then read the text from it. ( @Google, please make this easier.)

List<int> dataStore = []; 
    response.stream.listen((data) {  
     print("DataReceived: ${data.length}");
     dataStore.insertAll(dataStore.length, data);     
   }, onDone: () async {  
     Directory tempDir = await getTemporaryDirectory(); //Get temp folder using Path Provider
     String tempPath = tempDir.path;   //Get path to that location
      File file = File('$tempPath/test'); //Create a dummy file
      await file.writeAsBytes(dataStore); //Write to that file from the datastore you created from the Media stream
      String content = file.readAsStringSync(); // Read String from the file
      print(content); //Finally you have your text
      print("Task Done");  
   }, onError: (error) {  
     print("Some Error");  
   });  
like image 53
Yonkee Avatar answered Oct 22 '22 03:10

Yonkee