Using Offline Persistence in Firestore in a Flutter App

前端 未结 3 1008
天命终不由人
天命终不由人 2020-12-29 09:02

I\'m developing a app that uses Firebase\'s Firestore to send data to the web. One of the functions of the app is being able to save data in the device while being offline a

3条回答
  •  盖世英雄少女心
    2020-12-29 09:53

    when you use offline persistence in Firestore, don't use Transactions or await for response.

    so, change this :

      await Firestore.instance.collection('certificados').document((certID.toString()))
          .setData(finalDataMap);
    

    to this:

     Firestore.instance.collection('certificados').document((certID.toString()))
          .setData(finalDataMap);
    

    When you restore your internet connection your data will be sync automatically, even if you are in background.

    Doesn't work when your app is closed.

    Context Of Promises & Callbacks when Offline

    Why the above code change to remove "await" works.

    Reference: Firebase Video - How Do I Enable Offline Support 11:13

    Your callback won't be called and your promise won't complete until the document write has been successful on the server. This is why if your UI waits until the write completes to do something, it appears to freeze in "offline mode" even if the write was actually made to the local cache.

    It is OK to not use async / await, .then() or callbacks. Firestore will always "act" as if the data change was applied immediately, so you don't need to wait to be working with fresh data.

    You only need to use callbacks and promises when you need to be sure that a server write has happened, and you want to block other things from happening until you get that confirmation.

提交回复
热议问题