firebase_database 0.3.5

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

Firebase Realtime Database for Flutter

pub package

A Flutter plugin to use the Firebase Realtime Database 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_database as a dependency in your pubspec.yaml file.

Getting Started

See the example directory for a complete sample app using Firebase Realtime Database.

0.3.5

  • Enabled use in Swift projects.

0.3.4

  • Allow null values for Query startAt, endAt, and equalTo

0.3.3

  • Support to specify a database by URL if required

0.3.2

  • Fix warnings from the Dart 2.0 analyzer.
  • Simplified and upgraded Android project template to Android SDK 27.
  • Updated package description.

0.3.1

  • Fix function name collision when using Firebase Database and Cloud Firestore together on iOS.

0.3.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.

0.2.0

  • Support for multiple databases, new dependency on firebase_core
  • Relax GMS dependency to 11.+

0.1.4

  • Add FLT prefix to iOS types
  • Avoid error when clearing FirebaseSortedList

0.1.3

  • Fix memory leak in FirebaseAnimatedList
  • Change GMS dependency to 11.4.+

0.1.2

  • Change GMS dependency to 11.+

0.1.1

  • Add RTDB transaction support.

0.1.0+1

  • Aligned author name with rest of repo.

0.1.0

  • Breaking Change: Added current list index to the type signature of itemBuilder for FirebaseAnimatedList.

0.0.14

  • Fix FirebaseSortedList to show data changes.

0.0.13

  • Fixed lingering value/child listeners.

0.0.12

  • Updated to Firebase SDK to always use latest patch version for 11.0.x builds

0.0.11

  • Fixes startAt/endAt on iOS when used without a key

0.0.10

  • Added workaround for inconsistent numeric types when using keepSynced on iOS
  • Bug fixes to Query handling

0.0.9

  • Updated to Firebase SDK Version 11.0.1

0.0.8

  • Added missing offline persistence and query functionality on Android
  • Fixed startAt query behavior on iOS
  • Persistence methods no longer throw errors on failure, return false instead
  • Updates to docs and tests

0.0.7

  • Fixed offline persistence on iOS

0.0.6

  • Various APIs added to FirebaseDatabase and Query
  • Added removal and priority to DatabaseReference
  • Improved documentation
  • Added unit tests

0.0.5

  • Fixed analyzer warnings

0.0.4

  • Removed stub code and replaced it with support for more event types, paths, auth
  • Improved example

0.0.3

  • Updated README.md
  • Bumped buildToolsVersion to 25.0.3
  • Added example app

0.0.2

  • Fix compilation error

0.0.1

  • Initial Release

example/lib/main.dart

// Copyright 2017, the Flutter project authors.  Please see the AUTHORS file
// for details. 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' show Platform;

import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:firebase_database/ui/firebase_animated_list.dart';

final FirebaseApp app = new FirebaseApp(
  name: 'db2',
  options: Platform.isIOS
      ? const FirebaseOptions(
          googleAppID: '1:297855924061:ios:c6de2b69b03a5be8',
          gcmSenderID: '297855924061',
          databaseURL: 'https://flutterfire-cd2f7.firebaseio.com',
        )
      : const FirebaseOptions(
          googleAppID: '1:297855924061:android:669871c998cc21bd',
          apiKey: 'AIzaSyD_shO5mfO9lhy2TVWhfo1VUmARKlG4suk',
          databaseURL: 'https://flutterfire-cd2f7.firebaseio.com',
        ),
);

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Database Example',
      home: new MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter;
  DatabaseReference _counterRef;
  DatabaseReference _messagesRef;
  StreamSubscription<Event> _counterSubscription;
  StreamSubscription<Event> _messagesSubscription;
  bool _anchorToBottom = false;

  String _kTestKey = 'Hello';
  String _kTestValue = 'world!';
  DatabaseError _error;

  @override
  void initState() {
    super.initState();
    FirebaseApp.configure(name: app.name, options: app.options);
    // Demonstrates configuring to the database using a file
    _counterRef = FirebaseDatabase.instance.reference().child('counter');
    // Demonstrates configuring the database directly
    final FirebaseDatabase database = new FirebaseDatabase(app: app);
    _messagesRef = database.reference().child('messages');
    database.reference().child('counter').once().then((DataSnapshot snapshot) {
      print('Connected to second database and read ${snapshot.value}');
    });
    database.setPersistenceEnabled(true);
    database.setPersistenceCacheSizeBytes(10000000);
    _counterRef.keepSynced(true);
    _counterSubscription = _counterRef.onValue.listen((Event event) {
      setState(() {
        _error = null;
        _counter = event.snapshot.value ?? 0;
      });
    }, onError: (DatabaseError error) {
      setState(() {
        _error = error;
      });
    });
    _messagesSubscription =
        _messagesRef.limitToLast(10).onChildAdded.listen((Event event) {
      print('Child added: ${event.snapshot.value}');
    }, onError: (DatabaseError error) {
      print('Error: ${error.code} ${error.message}');
    });
  }

  @override
  void dispose() {
    super.dispose();
    _messagesSubscription.cancel();
    _counterSubscription.cancel();
  }

  Future<Null> _increment() async {
    await FirebaseAuth.instance.signInAnonymously();
    // Increment counter in transaction.
    final TransactionResult transactionResult =
        await _counterRef.runTransaction((MutableData mutableData) async {
      mutableData.value = (mutableData.value ?? 0) + 1;
      return mutableData;
    });

    if (transactionResult.committed) {
      _messagesRef.push().set(<String, String>{
        _kTestKey: '$_kTestValue ${transactionResult.dataSnapshot.value}'
      });
    } else {
      print('Transaction not committed.');
      if (transactionResult.error != null) {
        print(transactionResult.error.message);
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: const Text('Flutter Database Example'),
      ),
      body: new Column(
        children: <Widget>[
          new Flexible(
            child: new Center(
              child: _error == null
                  ? new Text(
                      'Button tapped $_counter time${ _counter == 1 ? '' : 's' }.\n\n'
                          'This includes all devices, ever.',
                    )
                  : new Text(
                      'Error retrieving button tap count:\n${_error.message}',
                    ),
            ),
          ),
          new ListTile(
            leading: new Checkbox(
              onChanged: (bool value) {
                setState(() {
                  _anchorToBottom = value;
                });
              },
              value: _anchorToBottom,
            ),
            title: const Text('Anchor to bottom'),
          ),
          new Flexible(
            child: new FirebaseAnimatedList(
              key: new ValueKey<bool>(_anchorToBottom),
              query: _messagesRef,
              reverse: _anchorToBottom,
              sort: _anchorToBottom
                  ? (DataSnapshot a, DataSnapshot b) => b.key.compareTo(a.key)
                  : null,
              itemBuilder: (BuildContext context, DataSnapshot snapshot,
                  Animation<double> animation, int index) {
                return new SizeTransition(
                  sizeFactor: animation,
                  child: new Text("$index: ${snapshot.value.toString()}"),
                );
              },
            ),
          ),
        ],
      ),
      floatingActionButton: new FloatingActionButton(
        onPressed: _increment,
        tooltip: 'Increment',
        child: new Icon(Icons.add),
      ),
    );
  }
}

1. Depend on it

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


dependencies:
  firebase_database: "^0.3.5"

2. Install it

You can install packages from the command line:

with pub:


$ pub get

with Flutter:


$ flutter packages get

Alternatively, your editor might support pub get or 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_database/firebase_database.dart';
        
Version Uploaded Documentation Archive
0.3.5 Feb 15, 2018 Go to the documentation of firebase_database 0.3.5 Download firebase_database 0.3.5 archive
0.3.4 Jan 17, 2018 Go to the documentation of firebase_database 0.3.4 Download firebase_database 0.3.4 archive
0.3.3 Jan 13, 2018 Go to the documentation of firebase_database 0.3.3 Download firebase_database 0.3.3 archive
0.3.2 Jan 11, 2018 Go to the documentation of firebase_database 0.3.2 Download firebase_database 0.3.2 archive
0.3.1 Jan 5, 2018 Go to the documentation of firebase_database 0.3.1 Download firebase_database 0.3.1 archive
0.3.0 Dec 20, 2017 Go to the documentation of firebase_database 0.3.0 Download firebase_database 0.3.0 archive
0.2.0 Dec 20, 2017 Go to the documentation of firebase_database 0.2.0 Download firebase_database 0.2.0 archive
0.1.4 Dec 3, 2017 Go to the documentation of firebase_database 0.1.4 Download firebase_database 0.1.4 archive
0.1.3 Nov 28, 2017 Go to the documentation of firebase_database 0.1.3 Download firebase_database 0.1.3 archive
0.1.2 Oct 17, 2017 Go to the documentation of firebase_database 0.1.2 Download firebase_database 0.1.2 archive

All 25 versions...

Analysis

This feature is new.
We welcome feedback.
More details: scoring.

We analyzed this package, and provided a score, details, and suggestions below.

  • tool failures on Feb 15, 2018
  • Dart: 2.0.0-dev.20.0
  • pana: 0.10.1
  • Flutter: 0.0.22

Scores

Popularity:
Describes how popular the package is relative to other packages. [more]
99 / 100
Health:
Code health derived from static analysis. [more]
100 / 100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
76 / 100
Overall score:
Weighted score of the above. [more]
95

Platforms

Detected platforms: unsure

Error(s) prevent platform classification.

Suggestions

  • Fix dependencies in pubspec.yaml.

    Running flutter packages pub upgrade failed with the following output:

    ERR: Invalid argument(s): Minimum version ("2.0.0-dev.23.0") must be less than maximum ("2.0.0-dev.16.0").
    ERR: package:pub_semver/src/version_range.dart 59         new VersionRange
     package:pub/src/pubspec.dart 366                     Pubspec._ensureEnvironment
     package:pub/src/pubspec.dart 331                     Pubspec.dartSdkConstraint
     package:pub/src/solver/backtracking_solver.dart 511  BacktrackingSolver._checkPubspecMatchesSdkConstraint
     package:pub/src/solver/backtracking_solver.dart 474  BacktrackingSolver._checkVersion
     ===== asynchronous gap ===========================
     package:pub/src/solver/backtracking_solver.dart 432  BacktrackingSolver._findValidVersion.<fn>
     ===== asynchronous gap ===========================
     dart:async                                           Future.doWhile
     package:pub/src/solver/backtracking_solver.dart 430  BacktrackingSolver._findValidVersion
     package:pub/src/solver/backtracking_solver.dart 337  BacktrackingSolver._versionQueueFor
     ===== asynchronous gap ===========================
     package:pub/src/solver/backtracking_solver.dart 290  BacktrackingSolver._solve.<fn>
     ===== asynchronous gap ===========================
     dart:async                                           _completeOnAsyncReturn
     package:pub/src/solver/backtracking_solver.dart 315  BacktrackingSolver._solve.<fn>
     dart:async                                           _completeOnAsyncReturn
     package:pub/src/solver/version_selection.dart 64     VersionSelection.select
     dart:async                                           _completeOnAsyncReturn
     package:pub/src/solver/version_selection.dart 91     VersionSelection._addDependencies
     dart:async                                           _completeOnAsyncReturn
     package:pub/src/solver/version_selection.dart 91     VersionSelection._addDependencies
    ERR: This is an unexpected error. Please run
     
         pub --trace upgrade --verbosity io --no-precompile
     
     and include the logs in an issue on https://github.com/dart-lang/pub/issues/new
    
  • Fix platform conflicts.

    Make sure none of the libraries use mutually exclusive dependendencies.

  • Fix issues reported by dartanalyzer.

    dartanalyzer reported 1 error(s) and 0 warning(s).

  • Package is pre-v1 release.

    While there is nothing inherently wrong with versions of 0.*.*, it usually means that the author is still experimenting with the general direction API.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=1.8.0 <2.0.0