I am having a problem with Firebase Realtime Database(RTDB) with Flutter. I am using RTDB with anonymous authentication in a project.
Sometimes, when I run the app on either device or simulator, it gives me the error in the title: [firebase_database/permission-denied] Client doesn't have permission to access the desired data.
If I rerun the app without touching anything, the app runs as expected, without any permission error. I am facing this problem about 1 in 20 or 1 in 30 times.
The original ruleset for my RTDB was (since I am using anonymous sign-in):
{
"rules": {
".read": "auth != null",
".write": "auth != null",
}
}
Then I thought this is the problem and changed the rules as, but did not remove the code piece for anonymous authentication:
{
"rules": {
".read": true, //"auth != null",
".write": false //"auth != null",
}
}
EDIT:
It turns out that the problem holds even auth feature is not used. The most important point I realized is that likelihood of the problem increases with decreasing wifi signal strength. I simplified the code as:
void main () async {
WidgetsFlutterBinding.ensureInitialized();
FirebaseApp app = await Firebase.initializeApp();
await FirebaseDatabase.instance.ref()
.child('otomodels')
.get()
.then((DataSnapshot? snap) => otomodels = snap!.value);
print('It is OK');
}
I ran the app on an ios simulator. The logs when the problem occurs are:
2021-12-12 15:12:44.915068+0300 Runner[39169:341996] Metal API Validation Enabled
2021-12-12 15:12:45.367316+0300 Runner[39169:341996] Writing analzed variants.
2021-12-12 15:12:45.410703+0300 Runner[39169:342197] 8.9.0 - [Firebase/Core][I-COR000005] No app has been configured yet.
2021-12-12 15:12:49.494185+0300 Runner[39169:342212] [VERBOSE-2:ui_dart_state.cc(209)] Unhandled Exception: [firebase_database/permission-denied] Client doesn't have permission to access the desired data.
#0 StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:607:7)
#1 MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:167:18)
#2 MethodChannel.invokeMapMethod (package:flutter/src/services/platform_channel.dart:367:43)
#3 MethodChannelQuery.get (package:firebase_database_platform_interface/src/method_channel/method_channel_query.dart:74:22)
#4 Query.get (package:firebase_database/src/query.dart:21:27)
#5 main (package:myProject/main.dart:29:3)
#0 MethodChannelQuery.get (package:firebase_database_platform_interface/src/method_channel/method_channel_query.dart:86:7)
#1 Query.get (package:firebase_database/src/query.dart:21:27)
#2 main (package:myProject/main.dart:29:3)