การคงอยู่ของสถานะด้วย HydratedBloc
จัดลำดับและกู้คืนสถานะ BLoC โดยอัตโนมัติเมื่อแอปเริ่มทำงานใหม่ด้วย hydrated_bloc
การคงอยู่ของสถานะด้วย HydratedBloc เป็นบทเรียน Flutter Mobile Development ฟรีบน CoddyKit นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Flutter Mobile Development และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Flutter Mobile Development มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
Why Persist BLoC State?
By default, a Bloc or Cubit loses everything when the app process is killed. Reopening the app re-runs the initial state, so the user's last selections, cart contents, or theme are gone.
hydrated_bloc solves this without you writing manual save/load code. It transparently:
- Serializes each new state to local storage as it is emitted
- Restores the last state automatically when the BLoC is recreated
This is ideal for UI preferences, onboarding flags, and small session data that should survive an app restart.
Setup and Storage Initialization
Add the packages to pubspec.yaml:
hydrated_blocprovidesHydratedBlocandHydratedCubitpath_providersupplies a writable directory on the device
Before your app runs, you must build a storage backend and assign it to HydratedBloc.storage. Because this touches platform channels, wrap it with WidgetsFlutterBinding.ensureInitialized().
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
HydratedBloc.storage = await HydratedStorage.build(
storageDirectory: kIsWeb
? HydratedStorageDirectory.web
: HydratedStorageDirectory(
(await getApplicationDocumentsDirectory()).path,
),
);
runApp(const MyApp());
}From Cubit to HydratedCubit
The simplest way to persist state is to extend HydratedCubit instead of Cubit. You must override two methods:
toJson(state)converts the state into a JSON-encodableMap(or returnsnullto skip persistence)fromJson(json)rebuilds the state from that map (or returnsnullto fall back to the constructor's initial state)
Here a counter survives restarts with just a few lines.
class CounterCubit extends HydratedCubit<int> {
CounterCubit() : super(0);
void increment() => emit(state + 1);
void decrement() => emit(state - 1);
@override
int? fromJson(Map<String, dynamic> json) => json['value'] as int?;
@override
Map<String, dynamic>? toJson(int state) => {'value': state};
}How fromJson and toJson Drive Persistence
The flow is fully automatic once the methods are defined:
- On every
emit, hydrated_bloc callstoJsonand writes the result to storage keyed by the BLoC'sstorageToken. - When the BLoC is constructed, the base class reads stored JSON and calls
fromJson; the returned value becomes the starting state, overriding the value passed tosuper(...).
If fromJson returns null (no data yet, or a decode failure), the constructor's initial state is used instead. This null-fallback is your safety net.
Persisting a Custom State Class
Real apps rarely store a plain int. For a custom state, map every field you care about in toJson and read it back in fromJson. Below, a settings state with a theme flag and font scale is fully serialized.
Keep the JSON shape stable and explicit so future versions can still read old data.
class SettingsState {
final bool darkMode;
final double fontScale;
const SettingsState({required this.darkMode, required this.fontScale});
Map<String, dynamic> toMap() =>
{'darkMode': darkMode, 'fontScale': fontScale};
factory SettingsState.fromMap(Map<String, dynamic> m) => SettingsState(
darkMode: m['darkMode'] as bool? ?? false,
fontScale: (m['fontScale'] as num?)?.toDouble() ?? 1.0,
);
}
class SettingsCubit extends HydratedCubit<SettingsState> {
SettingsCubit()
: super(const SettingsState(darkMode: false, fontScale: 1.0));
void toggleDark() =>
emit(SettingsState(darkMode: !state.darkMode, fontScale: state.fontScale));
@override
SettingsState? fromJson(Map<String, dynamic> json) =>
SettingsState.fromMap(json);
@override
Map<String, dynamic>? toJson(SettingsState state) => state.toMap();
}Using HydratedBloc with Events
For event-driven logic, extend HydratedBloc instead of HydratedCubit. The toJson/fromJson contract is identical; only state production changes (you register event handlers with on<Event>).
This is the right choice when transitions need event semantics, logging, or transformers.
sealed class CartEvent {}
class ItemAdded extends CartEvent {
final String sku;
ItemAdded(this.sku);
}
class CartBloc extends HydratedBloc<CartEvent, List<String>> {
CartBloc() : super(const []) {
on<ItemAdded>((event, emit) => emit([...state, event.sku]));
}
@override
List<String>? fromJson(Map<String, dynamic> json) =>
(json['items'] as List?)?.cast<String>();
@override
Map<String, dynamic>? toJson(List<String> state) => {'items': state};
}Pure Serialization Logic (Testable)
The heart of persistence is plain Dart: turning an object into a Map and back. You can unit-test that round-trip with no Flutter, no storage, and no device. Below is a standalone program proving the encode/decode is lossless.
Treat your toJson/fromJson as ordinary functions and test them in isolation before wiring them into a BLoC.
import 'dart:convert';
Map<String, dynamic> toJson(int value) => {'value': value};
int? fromJson(Map<String, dynamic> json) => json['value'] as int?;
void main() {
final state = 42;
final encoded = jsonEncode(toJson(state));
print('stored: $encoded');
final decoded = fromJson(jsonDecode(encoded) as Map<String, dynamic>);
print('restored: $decoded');
print('lossless: ${decoded == state}');
}Schema Migration with a Version Field
Once your app ships, old serialized data lives on users' devices. If you add or rename fields, naive fromJson can crash or read garbage. The standard defense is a version field written into the JSON.
On read, branch on the version and upgrade old shapes. This demo migrates a v1 payload (single name) into v2 (firstName/lastName).
import 'dart:convert';
Map<String, dynamic> migrate(Map<String, dynamic> json) {
final version = json['v'] as int? ?? 1;
if (version >= 2) return json;
final parts = (json['name'] as String).split(' ');
return {
'v': 2,
'firstName': parts.first,
'lastName': parts.length > 1 ? parts.last : '',
};
}
void main() {
final oldData = jsonDecode('{"v":1,"name":"Ada Lovelace"}');
final upgraded = migrate(oldData as Map<String, dynamic>);
print(upgraded);
}Defensive fromJson: Surviving Corrupt Data
If fromJson throws, hydrated_bloc catches it and falls back to the initial state, but a partially valid map can still produce a bad state. Make decoding total: validate types, supply defaults, and return null when the data is unusable.
Returning null is intentional and safe — it tells hydrated_bloc to use the constructor's initial state instead.
@override
SettingsState? fromJson(Map<String, dynamic> json) {
try {
final scale = (json['fontScale'] as num?)?.toDouble();
if (scale == null || scale <= 0) return null; // reject bad data
return SettingsState(
darkMode: json['darkMode'] as bool? ?? false,
fontScale: scale,
);
} catch (_) {
return null; // fall back to initial state
}
}Selective Persistence and Clearing State
You do not have to persist every state. Returning null from toJson skips writing for that emission — useful for transient loading or error states you would not want restored.
To wipe stored data, call clear() on the instance (removes just this BLoC's entry) or HydratedBloc.storage.clear() (wipes everything, e.g. on logout).
class AuthCubit extends HydratedCubit<AuthState> {
AuthCubit() : super(const Unauthenticated());
void logout() {
clear(); // remove this cubit's persisted entry
emit(const Unauthenticated());
}
@override
Map<String, dynamic>? toJson(AuthState state) =>
state is Authenticated ? {'token': state.token} : null; // skip others
@override
AuthState? fromJson(Map<String, dynamic> json) =>
json['token'] is String ? Authenticated(json['token'] as String) : null;
}Multiple Instances and storageToken
hydrated_bloc keys persisted data by a storageToken, which defaults to runtimeType. So two instances of the same BLoC class share one storage slot and will overwrite each other.
If you need per-entity persistence (for example, one cubit per chat room), override id so each instance gets a unique token like ChatCubit-room42.
class ChatCubit extends HydratedCubit<List<String>> {
final String roomId;
ChatCubit(this.roomId) : super(const []);
@override
String get id => roomId; // token becomes 'ChatCubit-$roomId'
@override
List<String>? fromJson(Map<String, dynamic> json) =>
(json['messages'] as List?)?.cast<String>();
@override
Map<String, dynamic>? toJson(List<String> state) => {'messages': state};
}Quick Check
A teammate reports that a HydratedCubit emits transient Loading states, and after an app restart the UI is sometimes stuck showing a spinner that never resolves. What is the cleanest fix?
Recap
You can now persist BLoC state across restarts with hydrated_bloc:
- Initialize
HydratedBloc.storageinmain()afterensureInitialized(). - Extend
HydratedCubitorHydratedBlocand overridetoJson/fromJson. - Restoration is automatic on construction;
nullfromfromJsonsafely falls back to the initial state. - Return
nullfromtoJsonto skip persisting transient states, and useclear()on logout. - Guard against corrupt data with defensive decoding and version-based migration.
- Override
idwhen you need per-instance storage tokens.
Keep persisted payloads small and your serialization pure and tested — that is what makes restart-safe state reliable at scale.
คำถามที่พบบ่อย
บทเรียน “การคงอยู่ของสถานะด้วย HydratedBloc” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “การคงอยู่ของสถานะด้วย HydratedBloc” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Flutter Mobile Development ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Flutter Mobile Development มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “การคงอยู่ของสถานะด้วย HydratedBloc”
จัดลำดับและกู้คืนสถานะ BLoC โดยอัตโนมัติเมื่อแอปเริ่มทำงานใหม่ด้วย hydrated_bloc คุณปฏิบัติ Flutter Mobile Development ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Flutter Mobile Development หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน Flutter Mobile Development บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน
บทเรียน “การคงอยู่ของสถานะด้วย HydratedBloc” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน Flutter Mobile Development นี้ได้ไหม
ได้ บทเรียน Flutter Mobile Development ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- เหตุการณ์ สถานะ และการตัดสินใจระหว่าง Cubit กับ Bloc
- ตัวแปลงสตรีมและการหน่วงเหตุการณ์ใน BLoC
- การคงอยู่ของสถานะด้วย HydratedBloc
- การทดสอบ BLoC ด้วย bloc_test และ Mocktail