D
State ManagementAdvanced50 XP4 min read

How do you implement optimistic updates in Flutter?

TL;DR: Optimistic updates apply the expected state change immediately in the UI before the API confirms it. If the API fails, you roll back to the previous state and show an error.

Full Answer

Optimistic updates make UIs feel faster — especially for actions like liking a post or adding to cart. The UI assumes success, then corrects if the server disagrees.

  • 1. Save the current state as previousState
  • 2. Immediately emit the optimistic new state
  • 3. Call the API in the background
  • 4. On success: do nothing (already showing correct state)
  • 5. On failure: emit previousState + error message
🎯

Riverpod's ref.invalidate() or BLoC's rollback pattern both work for this. The key is always keeping a reference to the state before the optimistic change.

Code Examples

dartOptimistic like toggle in a Cubit
Output
Like icon toggles instantly on tap; reverts with error message if API call fails

Common Mistakes

  • Not saving previous state before optimistic update — can't rollback on error
  • Showing the rollback without an error message — user sees UI flicker with no explanation

Interview Tip

💡

This question tests product thinking, not just Flutter knowledge. Mentioning user experience (instant feedback) alongside technical implementation impresses product-focused interviewers.

#optimistic-update#rollback#UX#state-management#networking