Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ValueEventListener on firebase database in flutter app

I am learning android app development in flutter. I have started from flutter chat app example. In the Enable data syncing section , It is explained to use Firebase Database like below.

final DBreference = FirebaseDatabase.instance.reference().child('messages');

Also the push() and set() methods are working fine.

When i try to listen to events on child using ValueEventListener. The DBreference created above has no methods like addListenerForSingleValueEvent or addValueEventListener.

My main goal is to retrieve value of child as expalined in SO answers Retrieving child value -firebase- or Checking if a particular value exists in the firebase database

I m getting undefined class ValueEventListener
if i create a new ValueEventListener, i tried by importing

import 'com.google.firebase.database.ValueEventListener';

I m unable to import this path as well. Same error for addListenerForSingleValueEvent or addValueEventListener.

I am using android studio 3.1

like image 992
Hummingbird Avatar asked Apr 27 '18 19:04

Hummingbird


People also ask

How do I display data from Firebase database in Flutter?

To use Flutter with Firebase, you will first need to set dependencies in the pubspec file. You will also have to import firestore , i.e., the database provided by Firebase for data handling. Now, import the Firebase dependencies into your Dart file. import 'package:cloud_firestore/cloud_firestore.

Is Firebase a good backend for Flutter?

Firebase is a great backend solution for anyone that wants to use authentication, databases, cloud functions, ads and countless other features within an app luckily for us, Flutter has official support for Firebase with the FlutterFire set of libraries.


1 Answers

Use

var subscription = FirebaseDatabase.instance
.reference()
.child('messages')
.onXxx
.listen((event) {
  // process event
});

where onXxx is one of

  • value
  • onChildAdded
  • onChildRemoved
  • onChildChanged

To end the subscription you can use

subscription.cancel();
like image 184
Günter Zöchbauer Avatar answered Sep 19 '22 13:09

Günter Zöchbauer