firebase_storage 1.0.4

  • README.md
  • CHANGELOG.md
  • Example
  • Installing
  • Versions
  • 100

Firebase Cloud Storage for Flutter

pub package

A Flutter plugin to use the Firebase Cloud Storage API.

For Flutter plugins for other Firebase products, see FlutterFire.md.

Note: This plugin is still under development, and some APIs might not be available yet. Feedback and Pull Requests are most welcome!

Usage

To use this plugin, add firebase_storage as a dependency in your pubspec.yaml file.

Getting Started

See the example directory for a complete sample app using Firebase Cloud Storage.

1.0.4

  • Bump Android dependencies to latest.

1.0.3

  • Added monitoring of StorageUploadTask via events stream.
  • Added support for StorageUploadTask functions: pause, resume, cancel.
  • Set http version to be compatible with flutter_test.

1.0.2

  • Added missing http package dependency.

1.0.1

  • Bump Android and Firebase dependency versions.

1.0.0

  • Breaking change. Make StorageUploadTask implementation classes private.
  • Bump to released version

0.3.7

  • Updated Gradle tooling to match Android Studio 3.1.2.

0.3.6

  • Added support for custom metadata.

0.3.5

  • Updated iOS implementation to reflect Firebase API changes.

0.3.4

  • Added timeout properties to FirebaseStorage.

0.3.3

  • Added support for initialization with a custom Firebase app.

0.3.2

  • Added support for StorageReference writeToFile.

0.3.1

  • Added support for StorageReference functions: getParent, getRoot, getStorage, getName, getPath, getBucket.

0.3.0

  • Breaking change. Changed StorageUploadTask to abstract, removed the 'file' field, and made 'path' and 'metadata' private. Added two subclasses: StorageFileUploadTask and StorageDataUploadTask.
  • Deprecated the put function and added putFile and putData to upload files and bytes respectively.

0.2.6

  • Added support for updateMetadata.

0.2.5

  • Added StorageMetadata class, support for getMetadata, and support for uploading file with metadata.

0.2.4

  • Updated Google Play Services dependencies to version 15.0.0.

0.2.3

  • Updated package channel name and made channel visible for testing

0.2.2

  • Simplified podspec for Cocoapods 1.5.0, avoiding link issues in app archives.

0.2.1

  • Added support for getDownloadUrl.

0.2.0

  • Breaking change. Set SDK constraints to match the Flutter beta release.

0.1.5

  • Fix Dart 2 type errors.

0.1.4

  • Enabled use in Swift projects.

0.1.3

  • Added StorageReference path getter to retrieve the path component for the storage node.

0.1.2

  • Added StorageReference delete function to remove files from Firebase.

0.1.1

  • Simplified and upgraded Android project template to Android SDK 27.
  • Updated package description.

0.1.0

  • Breaking change. Upgraded to Gradle 4.1 and Android Studio Gradle plugin 3.0.1. Older Flutter projects need to upgrade their Gradle setup as well in order to use this version of the plugin. Instructions can be found here.
  • Relaxed GMS dependency to [11.4.0,12.0[

0.0.8

  • Added FLT prefix to iOS types
  • Change GMS dependency to 11.4.+

0.0.7

  • Change GMS dependency to 11.+

0.0.6

  • Added StorageReference getData function to download files into memory.

0.0.5+1

  • Aligned author name with rest of repo.

0.0.5

  • Updated to Firebase SDK to always use latest patch version for 11.0.x builds
  • Fix crash when encountering upload failure

0.0.4

  • Updated to Firebase SDK Version 11.0.1

0.0.3

  • Suppress unchecked warnings

0.0.2

  • Bumped buildToolsVersion to 25.0.3
  • Updated README

0.0.1

  • Initial Release

example/lib/main.dart

// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:async';
import 'dart:io';

import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:uuid/uuid.dart';

const String kTestString = 'Hello world!';

void main() async {
  final FirebaseApp app = await FirebaseApp.configure(
    name: 'test',
    options: FirebaseOptions(
      googleAppID: Platform.isIOS
          ? '1:159623150305:ios:4a213ef3dbd8997b'
          : '1:159623150305:android:ef48439a0cc0263d',
      gcmSenderID: '159623150305',
      apiKey: 'AIzaSyChk3KEG7QYrs4kQPLP1tjJNxBTbfCAdgg',
      projectID: 'flutter-firebase-plugins',
    ),
  );
  final FirebaseStorage storage = FirebaseStorage(
      app: app, storageBucket: 'gs://flutter-firebase-plugins.appspot.com');
  runApp(MyApp(storage: storage));
}

class MyApp extends StatelessWidget {
  MyApp({this.storage});
  final FirebaseStorage storage;

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Storage Example',
      home: MyHomePage(storage: storage),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({this.storage});
  final FirebaseStorage storage;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey();
  List<StorageUploadTask> _tasks = <StorageUploadTask>[];

  Future<Null> _uploadFile() async {
    final String uuid = Uuid().v1();
    final Directory systemTempDir = Directory.systemTemp;
    final File file = await File('${systemTempDir.path}/foo$uuid.txt').create();
    await file.writeAsString(kTestString);
    assert(await file.readAsString() == kTestString);
    final StorageReference ref =
        widget.storage.ref().child('text').child('foo$uuid.txt');
    final StorageUploadTask uploadTask = ref.putFile(
      file,
      StorageMetadata(
        contentLanguage: 'en',
        customMetadata: <String, String>{'activity': 'test'},
      ),
    );

    setState(() {
      _tasks.add(uploadTask);
    });
  }

  Future<Null> _downloadFile(StorageReference ref) async {
    final String url = await ref.getDownloadURL();
    final String uuid = Uuid().v1();
    final http.Response downloadData = await http.get(url);
    final Directory systemTempDir = Directory.systemTemp;
    final File tempFile = File('${systemTempDir.path}/tmp$uuid.txt');
    if (tempFile.existsSync()) {
      await tempFile.delete();
    }
    await tempFile.create();
    assert(await tempFile.readAsString() == "");
    final StorageFileDownloadTask task = ref.writeToFile(tempFile);
    final int byteCount = (await task.future).totalByteCount;
    final String tempFileContents = await tempFile.readAsString();
    assert(tempFileContents == kTestString);
    assert(byteCount == kTestString.length);

    final String fileContents = downloadData.body;
    final String name = await ref.getName();
    final String bucket = await ref.getBucket();
    final String path = await ref.getPath();
    _scaffoldKey.currentState.showSnackBar(SnackBar(
      content: Text(
        'Success!\n Downloaded $name \n from url: $url @ bucket: $bucket\n '
            'at path: $path \n\nFile contents: "$fileContents" \n'
            'Wrote "$tempFileContents" to tmp.txt',
        style: const TextStyle(color: Color.fromARGB(255, 0, 155, 0)),
      ),
    ));
  }

  @override
  Widget build(BuildContext context) {
    final List<Widget> children = <Widget>[];
    _tasks.forEach((StorageUploadTask task) {
      final Widget tile = UploadTaskListTile(
        task: task,
        onDismissed: () => setState(() => _tasks.remove(task)),
        onDownload: () => _downloadFile(task.lastSnapshot.ref),
      );
      children.add(tile);
    });
    return Scaffold(
      key: _scaffoldKey,
      appBar: AppBar(
        title: const Text('Flutter Storage Example'),
        actions: <Widget>[
          IconButton(
            icon: const Icon(Icons.clear_all),
            onPressed:
                _tasks.isNotEmpty ? () => setState(() => _tasks.clear()) : null,
          )
        ],
      ),
      body: ListView(
        children: children,
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _uploadFile,
        tooltip: 'Upload',
        child: const Icon(Icons.file_upload),
      ),
    );
  }
}

class UploadTaskListTile extends StatelessWidget {
  const UploadTaskListTile(
      {Key key, this.task, this.onDismissed, this.onDownload})
      : super(key: key);

  final StorageUploadTask task;
  final VoidCallback onDismissed;
  final VoidCallback onDownload;

  String get status {
    String result;
    if (task.isComplete) {
      if (task.isSuccessful) {
        result = 'Complete';
      } else if (task.isCanceled) {
        result = 'Canceled';
      } else {
        result = 'Failed ERROR: ${task.lastSnapshot.error}';
      }
    } else if (task.isInProgress) {
      result = 'Uploading';
    } else if (task.isPaused) {
      result = 'Paused';
    }
    return result;
  }

  String _bytesTransferred(StorageTaskSnapshot snapshot) {
    return '${snapshot.bytesTransferred}/${snapshot.totalByteCount}';
  }

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<StorageTaskEvent>(
      stream: task.events,
      builder: (BuildContext context,
          AsyncSnapshot<StorageTaskEvent> asyncSnapshot) {
        Widget subtitle;
        if (asyncSnapshot.hasData) {
          final StorageTaskEvent event = asyncSnapshot.data;
          final StorageTaskSnapshot snapshot = event.snapshot;
          subtitle = Text('$status: ${_bytesTransferred(snapshot)} bytes sent');
        } else {
          subtitle = const Text('Starting...');
        }
        return Dismissible(
          key: Key(task.hashCode.toString()),
          onDismissed: (_) => onDismissed(),
          child: ListTile(
            title: Text('Upload Task #${task.hashCode}'),
            subtitle: subtitle,
            trailing: Row(
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                Offstage(
                  offstage: !task.isInProgress,
                  child: IconButton(
                    icon: const Icon(Icons.pause),
                    onPressed: () => task.pause(),
                  ),
                ),
                Offstage(
                  offstage: !task.isPaused,
                  child: IconButton(
                    icon: const Icon(Icons.file_upload),
                    onPressed: () => task.resume(),
                  ),
                ),
                Offstage(
                  offstage: task.isComplete,
                  child: IconButton(
                    icon: const Icon(Icons.cancel),
                    onPressed: () => task.cancel(),
                  ),
                ),
                Offstage(
                  offstage: !(task.isComplete && task.isSuccessful),
                  child: IconButton(
                    icon: const Icon(Icons.file_download),
                    onPressed: onDownload,
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }
}

Use this package as a library

1. Depend on it

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


dependencies:
  firebase_storage: ^1.0.4

2. Install it

You can install packages from the command line:

with Flutter:


$ flutter packages get

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

3. Import it

Now in your Dart code, you can use:


import 'package:firebase_storage/firebase_storage.dart';
  
Version Uploaded Documentation Archive
1.0.4 Oct 12, 2018 Go to the documentation of firebase_storage 1.0.4 Download firebase_storage 1.0.4 archive
1.0.3 Oct 4, 2018 Go to the documentation of firebase_storage 1.0.3 Download firebase_storage 1.0.3 archive
1.0.2 Aug 21, 2018 Go to the documentation of firebase_storage 1.0.2 Download firebase_storage 1.0.2 archive
1.0.1 Jul 23, 2018 Go to the documentation of firebase_storage 1.0.1 Download firebase_storage 1.0.1 archive
1.0.0 Jul 3, 2018 Go to the documentation of firebase_storage 1.0.0 Download firebase_storage 1.0.0 archive
0.3.7 Jun 1, 2018 Go to the documentation of firebase_storage 0.3.7 Download firebase_storage 0.3.7 archive
0.3.5 May 14, 2018 Go to the documentation of firebase_storage 0.3.5 Download firebase_storage 0.3.5 archive
0.3.4 May 7, 2018 Go to the documentation of firebase_storage 0.3.4 Download firebase_storage 0.3.4 archive
0.3.3 May 3, 2018 Go to the documentation of firebase_storage 0.3.3 Download firebase_storage 0.3.3 archive
0.3.2 May 1, 2018 Go to the documentation of firebase_storage 0.3.2 Download firebase_storage 0.3.2 archive

All 30 versions...

Popularity:
Describes how popular the package is relative to other packages. [more]
99
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]
100
Learn more about scoring.

We analyzed this package on Oct 12, 2018, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.0.0
  • pana: 0.12.4
  • Flutter: 0.9.5

Platforms

Detected platforms: Flutter

References Flutter, and has no conflicting libraries.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.0.0-dev.28.0 <3.0.0
firebase_core ^0.2.3 0.2.5+1
flutter 0.0.0
Transitive dependencies
collection 1.14.11
meta 1.1.6
sky_engine 0.0.99
typed_data 1.1.6
vector_math 2.0.8
Dev dependencies
flutter_test
http ^0.12.0
uuid ^1.0.0