Flutter: How to backup user data on Google drive like WhatsApp does?

931

Step 1

You need to have already created a Google Firebase Project, and enable Google Drive API from Google Developer Console. Note that you need to select the same project in Google Developer Console as you have created in Google Firebase.

Step 2

you need to log in with google to get googleSignInAccount and use dependencies

 googleapis: ^0.54.0  
 googleapis_auth: ^0.2.11 



class GoogleHttpClient extends IOClient {  
 Map<String, String> _headers;  
 GoogleHttpClient(this._headers) : super();  
 @override  
 Future<http.StreamedResponse> send(http.BaseRequest request) =>  
     super.send(request..headers.addAll(_headers));  
 @override  
 Future<http.Response> head(Object url, {Map<String, String> headers}) =>  
     super.head(url, headers: headers..addAll(_headers));  
}

Upload File to Google Drive

_uploadFileToGoogleDrive() async {  
   var client = GoogleHttpClient(await googleSignInAccount.authHeaders);  
   var drive = ga.DriveApi(client);  
   ga.File fileToUpload = ga.File();  
   var file = await FilePicker.getFile();  
   fileToUpload.parents = ["appDataFolder"];  
   fileToUpload.name = path.basename(file.absolute.path);  
   var response = await drive.files.create(  
     fileToUpload,  
     uploadMedia: ga.Media(file.openRead(), file.lengthSync()),  
   );  
   print(response);  
 } 

Download Google Drive File

Future<void> _downloadGoogleDriveFile(String fName, String gdID) async {  
   var client = GoogleHttpClient(await googleSignInAccount.authHeaders);  
   var drive = ga.DriveApi(client);  
   ga.Media file = await drive.files  
       .get(gdID, downloadOptions: ga.DownloadOptions.FullMedia);  
   print(file.stream);  
   
   final directory = await getExternalStorageDirectory();  
   print(directory.path);  
   final saveFile = File('${directory.path}/${new DateTime.now().millisecondsSinceEpoch}$fName');  
   List<int> dataStore = [];  
   file.stream.listen((data) {  
     print("DataReceived: ${data.length}");  
     dataStore.insertAll(dataStore.length, data);  
   }, onDone: () {  
     print("Task Done");  
     saveFile.writeAsBytes(dataStore);  
     print("File saved at ${saveFile.path}");  
   }, onError: (error) {  
     print("Some Error");  
   });  
 } 
Share:
931
Alexey Lo
Author by

Alexey Lo

Updated on December 31, 2022

Comments

  • Alexey Lo
    Alexey Lo over 1 year

    I want to to backup data in Backups on user Google Drive account and restore them.

    I have seen apps, like WhatsApp that allow users to login through google drive and do periodic backup to the user cloud.

    I don't want to use firebase cloud since the data is access by the user himself and not other users and it will be costly if the data is large. Is there any available package can do this? Or tutorial otherwise how to achieve this in flutter?