Isuru Bandara
Isuru Bandara

Reputation: 360

How to add Data to firestore when internet connection is not working?

I am new to flutter and I am trying to add Data to firestore when internet connection is not working, For example - I check the internet connection before adding the data, But My internet connection could work when I checking the connection and internet connection might not work when I adding data due to run out the data package or unstable connection. In that case, It does not return an error. In flutter, Then() does not trigger until data added to the server, Therefore, I how can I check pendingWrites? I should wait until data added to the cache to check pendingWrites. What is the best way to add Data when Internet connection is not working ?

Here is my code,

 SavePersonalData(this.firstName, this.lastName, this.birthDay, this.gender, 
this.userID, this.context);

 Future<void> saveUserData(){
return users.collection('users').doc(userID)
    .set({
  'first_name': firstName,
  'last_name': lastName,
  'birth_day': birthDay,
  'user_id': userID,
  "gender": gender==0?"Male":"Female",
  'account_created_on': FieldValue.serverTimestamp(),
})
    .then((value) => `//This is does not trigger until internet connection works`





 Navigator.push(context, MaterialPageRoute(builder: (context)=> SelectImage()))
print("data added to the databse")).timeout(Duration(seconds:5),onTimeout: ()=>{
  print("TimeOut")
})
    .catchError(
        (error) {
      print("Failed to add user: $error");
      
    } );

Upvotes: 0

Views: 1227

Answers (1)

Dharmaraj
Dharmaraj

Reputation: 50840

As per FlutterFire Documentation, Offline Persistence is enabled by default.

Firebase Docs says if you have offline persistence enabled, it'll sync all the changes when an internet connection is available. Although if your apps needs realtime interactions, then you should probably disable this.

Notable thing is you cannot use transactions when in offline mode. More details can be found here. Also as mentioned here, you don't need to use await if offline.

Upvotes: 2

Related Questions