Search code examples
firebasedartfluttergoogle-cloud-firestore

flutter app crash when there is low or no network connection


I have this IconButton which when I press it updates a field on my cloud Firestore DB.I do not get any problem if there is a healthy internet connection, how ever is there is no network or low signal I get a timed out error and this causes the app to crash. I have have wraped the function in a try{} catch{} block but still that doesn't help.

 onPressed: (){
                 try{
                  Firestore.instance.runTransaction((Transaction thistransaction)async{
                  DocumentSnapshot docSnapshot = await thistransaction
                  .get(snapshotDocuments[index].reference);
                  await thistransaction.update(docSnapshot.reference,
                   {'voteUpBool':!docSnapshot['voteUpBool']});

                  });
                }
                 catch(err){
                    print(err.toString());
                  }
                 },

Solution

  • you have to check internet or wifi available or not for that just add connectivity: ^0.3.1 dependency with latest version and follow the below code.

    import 'dart:io';
    ...
    try {
       final result = await InternetAddress.lookup('google.com');
       if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
           print('connected');
       }
     } on SocketException catch (_) {
        print('not connected');
     }