firebase-realtime-databasedartpersistenceflutteroffline-caching

Flutter Firebase Database persistence not working


I am using the firebase_database plugin in version 1.0.1 with flutter currently testing on android.

I access the database with a singleton.

 GlobalFBInstance._internal() {
   final firebaseInstance = FirebaseDatabase.instance;

   firebaseInstance.goOnline();
   firebaseInstance.setPersistenceEnabled(true);
   firebaseInstance.setPersistenceCacheSizeBytes(10000000);

   databaseRef = firebaseInstance.reference();
   databaseRef.keepSynced(true);

   storageRef = FirebaseStorage.instance.ref();
}

Everytime after an app restart the app needs internet to get the database. I thought with the persistence and keepsynced there is no need for internet? If I have a very bad connection(tested in the emulator and on a device) it takes forever to load a gridview containing four simple strings from the database.

When I load a datasnapshot with:

 Future<DataSnapshot> getDatabaseSnap(String location) async {
    var _newref = databaseRef.child(location);
    await _newref.keepSynced(true);
    return await _newref.once();
 }

it won't load if there the internet connection is slow.

What could be the reason for this? Is there a better way to make sure the database doesn't need a connection every time?

Thanks in advance.

Edit: When waiting for persistence I get false:

 bool ispersistant = await firebaseInstance.setPersistenceEnabled(true);

Solution

  • Don't use FirebaseInstance to toggle persistent storage. Use FirebaseDatabase object to hold the instance and then set it to enable.

    FirebaseDatabase database;
    database = FirebaseDatabase.instance;
    database.setPersistenceEnabled(true);
    database.setPersistenceCacheSizeBytes(10000000); // 10MB cache is enough