Chuyển đến nội dung chính

Bài đăng

Hiển thị các bài đăng có nhãn Drift

Flutter offline-first: database dưới máy mới là nguồn sự thật, không phải API

Phần lớn app Flutter được viết như một cái điều khiển từ xa mỏng dính cho REST API. Màn hình hiện lên, bắn một request, quay spinner, response về thì rebuild. Cache được gắn thêm sau, thường là một Map trong repository hoặc một cục blob trong shared_preferences , và cache bị coi như mẹo tăng tốc chứ không phải dữ liệu. Rồi app gặp thang máy, gặp hầm, gặp sóng 3G lúc 6 giờ chiều, hoặc gặp Wi‑Fi sân bay có captive portal trả HTTP 200 kèm một trang HTML cho mọi request. Spinner cứ quay. Người dùng bấm “lưu” ba lần. Hai trong ba lần đó rốt cuộc tới được server, và bạn có bản ghi trùng trên production. Offline-first không phải là một tính năng bạn thêm vào kiến trúc đó. Nó là một kiến trúc khác, và khác biệt gói gọn trong một câu: UI chỉ đọc và ghi database dưới máy, còn network là một tiến trình nền làm nhiệm vụ đối soát database đó với server. Không màn hình nào await một lời gọi HTTP. Không nút nào bị disable vì đang có request bay. API thôi làm nguồn sự thật và trở thành một bên ng...

Offline-first Flutter: the local database is the source of truth, not the API

Most Flutter apps are written as thin remote controls for a REST API. A screen appears, it fires a request, it shows a spinner, and when the response lands it rebuilds. Caching gets bolted on later, usually as a Map in a repository class or a shared_preferences blob, and the cache is treated as a performance trick rather than as data. Then the app meets a lift, a tunnel, a Vietnamese 3G cell at 6pm, or an airport Wi‑Fi captive portal that answers every request with an HTTP 200 full of HTML. The spinner spins. The user taps “save” three times. Two of those taps eventually reach the server and you get duplicate rows in production. Offline-first is not a feature you add to that architecture. It is a different architecture, and the difference is one sentence: the UI reads and writes only the local database, and the network is a background process that reconciles that database with the server. No screen ever awaits an HTTP call. No button is disabled because a request is in flight. The...