Flutter/Firebase realtime database - handle network errors

880 views Asked by At

Firebase realtime database plugin: https://pub.dev/packages/firebase_database

My code to get values from database:

DataSnapshot d = await database.reference().child("my/child/node").once();
Map map = d.value;
String val1 = map["val1"];
String val2 = map["val2"];
String val3 = map["val3"];

It works. However, when there's no network connection, it waits endlessly. I want to catch error (unable to connect to database). Ho do I do that? Try/catch does not work, becasue no exception thrown, it just waits. I want to be informed about database connection error. Is it possible?

1

There are 1 answers

0
Shalabyer On BEST ANSWER

You could use a timout like this:

 if (await database
      .reference()
.child("my/child/node")
    .once()
    .timeout(Duration(seconds: 5), onTimeout: () {
print('Spent 5 seconds and no connection');
}).isNotEmpty) {
print('Connected successfully');
Map map = d.value;
String val1 = map["val1"];
String val2 = map["val2"];
String val3 = map["val3"];
}

But you should test it first because i didn't test isNotEmpty function in that case, you should test it and see what dose the line code

await database
      .reference()
.child("my/child/node")
    .once()

gives you on successful connection and make the "if" condition as it should. i.e:

  if (await http.get("google.com")
    .timeout(Duration(seconds: 5), onTimeout: () {
print('Spent 5 seconds and no connection');
})==200) {
print('Connected successfully');}

Or you can check for an internet connection before calling the database line. You could use something like this.

   import 'dart:io';

try {
final result = await InternetAddress.lookup('google.com');
if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
  DataSnapshot d = await database.reference().child("my/child/node").once();
  Map map = d.value;
  String val1 = map["val1"];
  String val2 = map["val2"];
  String val3 = map["val3"];    }
} on SocketException catch (_) {
print('not connected');
}