Upload Files In Google Drive Using Flutter

Haris Bin Nasir Avatar

·

·

We’ll learn how to incorporate Google Drive into the Flutter app in this tutorial. We’ll learn how to use Flutter to upload, list, and download files to Google Drive. For authentication, I used Google Plus, and then I went to Google Drive. I looked into the Google Drive API, but ultimately decided that this method is superior and more native. So let’s get started with our Flutter implementation of Google Drive.

How To Integrate Flutter With Google Drive?

The first and most fundamental step is to establish a new Flutter application. If you’re new to Flutter, check out my blog Create a First App in Flutter. “flutter gdrive” is the name of the app I made.

Integrate Google Plus Login into your project.

Now that you’ve created a Google Firebase Project, you can use the Google Developer Console to enable the Google Drive API. It’s important to note that you must choose the same project in Google Developer Console as you did in Google Firebase. It’s “Flutter Gdrive” in my instance. To learn more, look at the screenshots below.

We’ll now add the requirements needed to implement Google Drive Operations (Google API, Pick File to Upload & Download file in mobile storage). Please review the dependencies listed below.

Copied!
dependencies: flutter: sdk: flutter cupertino_icons: ^0.1.2 firebase_auth: ^0.15.2 google_sign_in: ^4.1.0 flutter_secure_storage: ^3.3.1+1 googleapis: ^0.54.0 googleapis_auth: ^0.2.11 path_provider: ^1.5.1 file_picker: ^1.3.8

Permissions for file reading and writing must be defined. To do so, add the following permissions to the AndroidManifest.xml file. (android/app/src/main/AndroidManifest.xml)

Copied!
<uses-permission android_name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android_name="android.permission.READ_EXTERNAL_STORAGE"/>

Now we’ll programmatically implement File Upload, Listing, and Download Login in the main.dart file. The class for mapping Google Auth Credentials to GoogleHttpClient Credentials is as follows.

Copied!
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)); }

The code for Google Plus login, logout, file upload to Google Drive, file download, and listing of uploaded files on Google Drive is shown below.

Google Login:

Copied!
Future<void> _loginWithGoogle() async { signedIn = await storage.read(key: "signedIn") == "true" ? true : false; googleSignIn.onCurrentUserChanged .listen((GoogleSignInAccount googleSignInAccount) async { if (googleSignInAccount != null) { _afterGoogleLogin(googleSignInAccount); } }); if (signedIn) { try { googleSignIn.signInSilently().whenComplete(() => () Array); } catch (e) { storage.write(key: "signedIn", value: "false").then((value) { setState(() { signedIn = false; }); }); } } else { final GoogleSignInAccount googleSignInAccount = await googleSignIn.signIn(); _afterGoogleLogin(googleSignInAccount); } } Future<void> _afterGoogleLogin(GoogleSignInAccount gSA) async { googleSignInAccount = gSA; final GoogleSignInAuthentication googleSignInAuthentication = await googleSignInAccount.authentication; final AuthCredential credential = GoogleAuthProvider.getCredential( accessToken: googleSignInAuthentication.accessToken, idToken: googleSignInAuthentication.idToken, ); final AuthResult authResult = await _auth.signInWithCredential(credential); final FirebaseUser user = authResult.user; assert(!user.isAnonymous); assert(await user.getIdToken() != null); final FirebaseUser currentUser = await _auth.currentUser(); assert(user.uid == currentUser.uid); print('signInWithGoogle succeeded: $user'); storage.write(key: "signedIn", value: "true").then((value) { setState(() { signedIn = true; }); }); }

Google Logout

Copied!
void _logoutFromGoogle() async { googleSignIn.signOut().then((value) { print("User Sign Out"); storage.write(key: "signedIn", value: "false").then((value) { setState(() { signedIn = false; }); }); }); }

Upload File to Google Drive

Copied!
_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); }

List Uploaded Files to Google Drive

Copied!
Future<void> _listGoogleDriveFiles() async { var client = GoogleHttpClient(await googleSignInAccount.authHeaders); var drive = ga.DriveApi(client); drive.files.list(spaces: 'appDataFolder').then((value) { setState(() { list = value; }); for (var i = 0; i < list.files.length; i++) { print("Id: ${list.files[i].id} File Name:${list.files[i].name}"); } }); }

Download Google Drive File

Copied!
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"); }); }

We’ve completed the Google Drive integration in Flutter. Please see my Github repository for the complete source code.

The google-services.json file is not included in the above source code; you must create your own firebase project and place it in the android->app folder.

Result

Conclusion

In this article we learned how to use Flutter to integrate Google Drive and conduct upload, download, and list actions. As always, If you have found this article useful do not forget to share it and leave a comment if you have any questions. Happy Coding

Leave a Reply

Your email address will not be published. Required fields are marked *