dropbox_client 0.7.1

  • Readme
  • Changelog
  • Example
  • Installing
  • 84

dropbox client #

pub package

A flutter plugin for accessing Dropbox.

Setup #

Register a Dropbox API app from https://www.dropbox.com/developers . You need dropbox key and dropbox secret.

For Android, add below in AndroidManifest.xml (replace DROPBOXKEY with your key)

    <activity
        android:name="com.dropbox.core.android.AuthActivity"
        android:configChanges="orientation|keyboard"
        android:launchMode="singleTask">
        <intent-filter>

            <!-- Change this to be db- followed by your app key -->
            <data android:scheme="db-DROPBOXKEY" />

            <action android:name="android.intent.action.VIEW" />

            <category android:name="android.intent.category.BROWSABLE" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </activity>

If you need more help setting up Android, please read https://github.com/dropbox/dropbox-sdk-java#setup .

For iOS,

  1. add below in Info.plist

     <key>LSApplicationQueriesSchemes</key>
       <array>
           <string>dbapi-8-emm</string>
           <string>dbapi-2</string>
       </array>
    
  2. add below in Info.plist (replace DROPBOXKEY with your key)

     <key>CFBundleURLTypes</key>
       <array>
         <dict>
           <key>CFBundleURLSchemes</key>
           <array>
             <string>db-DROPBOXKEY</string>
           </array>
           <key>CFBundleURLName</key>
           <string></string>
         </dict>
       </array>
    

3.a) If you are using Swift, add below code to AppDelegate.swift

    import ObjectiveDropboxOfficial

    // should be inside AppDelegate class
    override func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
      if let authResult = DBClientsManager.handleRedirectURL(url) {
          if authResult.isSuccess() {
              print("dropbox auth success")
          } else if (authResult.isCancel()) {
              print("dropbox auth cancel")
          } else if (authResult.isError()) {
              print("dropbox auth error \(authResult.errorDescription)")
          }
      }
      return true
    }

3.b) If you are using Objective C, add below code to AppDelegate.m

    #import <ObjectiveDropboxOfficial/ObjectiveDropboxOfficial.h>

    - (BOOL)application:(UIApplication *)app openURL:(NSURL *)url
        options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {
      DBOAuthResult *authResult = [DBClientsManager handleRedirectURL:url];
      if (authResult != nil) {
        if ([authResult isSuccess]) {
          NSLog(@"Success! User is logged into Dropbox.");
        } else if ([authResult isCancel]) {
          NSLog(@"Authorization flow was manually canceled by user!");
        } else if ([authResult isError]) {
          NSLog(@"Error: %@", authResult);
        }
      }
      return NO;
    }
  1. Update Deployment Target to iOS 9.0 or above from Xcode. (dropbox_client 0.7.0 and above)

If you need more help setting up for iOS, please read https://github.com/dropbox/dropbox-sdk-obj-c#get-started .

Usage #

import 'package:dropbox_client/dropbox_client.dart';

Future initDropbox() async {
    // init dropbox client. (call only once!)
    await Dropbox.init(dropbox_clientId, dropbox_key, dropbox_secret);
}

String accessToken;

Future testLogin() async {
  // this will run Dropbox app if possible, if not it will run authorization using a web browser.
  await Dropbox.authorize();
}

Future getAccessToken() async {
  accessToken = await Dropbox.getAccessToken();
}

Future loginWithAccessToken() async {
  await Dropbox.authorizeWithAccessToken(accessToken);
}

Future testLogout() async {
  // unlink removes authorization
  await Dropbox.unlink();
}

Future testListFolder() async {
  final result = await Dropbox.listFolder(''); // list root folder
  print(result);
  
  final url = await Dropbox.getTemporaryLink('/file.txt');
  print(url);
}

Future testUpload() async {
  final filepath = '/path/to/local/file.txt';
  final result = await Dropbox.upload(filepath, '/file.txt', (uploaded, total) {
    print('progress $uploaded / $total');
  });
}

Future testDownload() async {
  final filepath = '/path/to/local/file.txt';
  final result = await Dropbox.download('/dropbox_file.txt', filepath, (downloaded, total) {
    print('progress $downloaded / $total');
  });
}

Example can be found in example folder.

0.7.1 (2020/06/11) #

  • add unlink (logout) function
  • make download/upload progress callback optional
  • add documentation for swift integration

0.7.0 (2020/05/26) #

  • add download function.
  • update ios deployment target to 9.0
  • fix upload progress bug(not correctly reports cumulative bytes)

0.6.0 #

  • add upload function.

0.5.3 #

  • fix publish error

0.5.2 #

  • fix ios podspec error
  • add youtube video for example setup and demo.

0.5.1 #

  • fix error in README.md
  • longer description

0.5.0 #

  • Initial release.

example/lib/main.dart

import 'dart:io';

import 'package:flutter/material.dart';
import 'dart:async';
import 'package:dropbox_client/dropbox_client.dart';
import 'package:path_provider/path_provider.dart';
import 'package:shared_preferences/shared_preferences.dart';

const String dropbox_clientId = 'test-flutter-dropbox';
const String dropbox_key = 'dropbox_key';
const String dropbox_secret = 'dropbox_secret';

void main() {
  return runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(home: Home());
  }
}

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  String accessToken;
  bool showInstruction = false;

  @override
  void initState() {
    super.initState();

    initDropbox();
  }

  Future initDropbox() async {
    if (dropbox_key == 'dropbox_key') {
      showInstruction = true;
      return;
    }

    await Dropbox.init(dropbox_clientId, dropbox_key, dropbox_secret);

    SharedPreferences prefs = await SharedPreferences.getInstance();
    accessToken = prefs.getString('dropboxAccessToken');

    setState(() {});
  }

  Future<bool> checkAuthorized(bool authorize) async {
    final token = await Dropbox.getAccessToken();
    if (token != null) {
      if (accessToken == null || accessToken.isEmpty) {
        accessToken = token;
        SharedPreferences prefs = await SharedPreferences.getInstance();
        prefs.setString('dropboxAccessToken', accessToken);
      }
      return true;
    }
    if (authorize) {
      if (accessToken != null && accessToken.isNotEmpty) {
        await Dropbox.authorizeWithAccessToken(accessToken);
        final token = await Dropbox.getAccessToken();
        if (token != null) {
          print('authorizeWithAccessToken!');
          return true;
        }
      } else {
        await Dropbox.authorize();
        print('authorize!');
      }
    }
    return false;
  }

  Future authorize() async {
    await Dropbox.authorize();
  }

  Future unlink() async {
    await deleteAccessToken();
    await Dropbox.unlink();
  }

  Future authorizeWithAccessToken() async {
    await Dropbox.authorizeWithAccessToken(accessToken);
  }

  Future deleteAccessToken() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.remove('dropboxAccessToken');

    setState(() {
      accessToken = null;
    });
  }

  Future getAccountName() async {
    if (await checkAuthorized(true)) {
      final user = await Dropbox.getAccountName();
      print('user = $user');
    }
  }

  Future listFolder(path) async {
    if (await checkAuthorized(true)) {
      final result = await Dropbox.listFolder(path);
      setState(() {
        list = result;
      });
    }
  }

  Future uploadTest() async {
    if (await checkAuthorized(true)) {
      var tempDir = await getTemporaryDirectory();
      var filepath = '${tempDir.path}/test_upload.txt';
      File(filepath).writeAsStringSync(
          'contents.. from ' + (Platform.isIOS ? 'iOS' : 'Android') + '\n');

      final result =
          await Dropbox.upload(filepath, '/test_upload.txt', (uploaded, total) {
        print('progress $uploaded / $total');
      });
      print(result);
    }
  }

  Future downloadTest() async {
    if (await checkAuthorized(true)) {
      var tempDir = await getTemporaryDirectory();
      var filepath = '${tempDir.path}/test_download.zip'; // for iOS only!!
      print(filepath);

      final result = await Dropbox.download('/file_in_dropbox.zip', filepath,
          (downloaded, total) {
        print('progress $downloaded / $total');
      });

      print(result);
      print(File(filepath).statSync());
    }
  }

  Future<String> getTemporaryLink(path) async {
    final result = await Dropbox.getTemporaryLink(path);
    return result;
  }

  var list = List<dynamic>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Dropbox example app'),
      ),
      body: showInstruction
          ? Instructions()
          : Builder(
              builder: (context) {
                return Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: <Widget>[
                    Wrap(
                      children: <Widget>[
                        RaisedButton(
                          child: Text('authorize'),
                          onPressed: authorize,
                        ),
                        RaisedButton(
                          child: Text('authorizeWithAccessToken'),
                          onPressed: accessToken == null
                              ? null
                              : authorizeWithAccessToken,
                        ),
                        RaisedButton(
                          child: Text('unlink'),
                          onPressed: unlink,
                        ),
                        RaisedButton(
                          child: Text('list root folder'),
                          onPressed: () async {
                            await listFolder('');
                          },
                        ),
                        RaisedButton(
                          child: Text('test upload'),
                          onPressed: () async {
                            await uploadTest();
                          },
                        ),
                        RaisedButton(
                          child: Text('test download'),
                          onPressed: () async {
                            await downloadTest();
                          },
                        ),
                      ],
                    ),
                    Expanded(
                      child: ListView.builder(
                        itemCount: list.length,
                        itemBuilder: (context, index) {
                          final item = list[index];
                          final filesize = item['filesize'];
                          final path = item['pathLower'];
                          bool isFile = false;
                          var name = item['name'];
                          if (filesize == null) {
                            name += '/';
                          } else {
                            isFile = true;
                          }
                          return ListTile(
                              title: Text(name),
                              onTap: () async {
                                if (isFile) {
                                  final link = await getTemporaryLink(path);
                                  Scaffold.of(context).showSnackBar(
                                      SnackBar(content: Text(link)));
                                } else {
                                  await listFolder(path);
                                }
                              });
                        },
                      ),
                    ),
                  ],
                );
              },
            ),
    );
  }
}

class Instructions extends StatelessWidget {
  const Instructions({
    Key key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Text(
              'You need to get dropbox_key & dropbox_secret from https://www.dropbox.com/developers'),
          SizedBox(height: 20),
          Text('1. Update dropbox_key and dropbox_secret from main.dart'),
          SizedBox(height: 20),
          Text(
              "  const String dropbox_key = 'DROPBOXKEY';\n  const String dropbox_secret = 'DROPBOXSECRET';"),
          SizedBox(height: 20),
          Text(
              '2. (Android) Update dropbox_key from android/app/src/main/AndroidManifest.xml.\n  <data android:scheme="db-DROPBOXKEY" />'),
          SizedBox(height: 20),
          Text(
              '2. (iOS) Update dropbox_key from ios/Runner/Info.plist.\n  <string>db-DROPBOXKEY</string>'),
        ],
      ),
    );
  }
}

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  dropbox_client: ^0.7.1

2. Install it

You can install packages from the command line:

with Flutter:


$ flutter pub get

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:dropbox_client/dropbox_client.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
68
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
100
Overall:
Weighted score of the above. [more]
84
Learn more about scoring.

We analyzed this package on Jul 7, 2020, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.8.4
  • pana: 0.13.14
  • Flutter: 1.17.5

Analysis suggestions

Package does not support Flutter platform linux

Because:

  • package:dropbox_client/dropbox_client.dart that declares support for platforms: android, ios

Package does not support Flutter platform macos

Because:

  • package:dropbox_client/dropbox_client.dart that declares support for platforms: android, ios

Package does not support Flutter platform web

Because:

  • package:dropbox_client/dropbox_client.dart that declares support for platforms: android, ios

Package does not support Flutter platform windows

Because:

  • package:dropbox_client/dropbox_client.dart that declares support for platforms: android, ios

Package not compatible with SDK dart

Because:

  • dropbox_client that is a package requiring null.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.1.0 <3.0.0
flutter 0.0.0
Transitive dependencies
collection 1.14.12 1.14.13
meta 1.1.8 1.2.1
sky_engine 0.0.99
typed_data 1.1.6 1.2.0
vector_math 2.0.8
Dev dependencies
flutter_test