State Management Nâng Cao Trong Flutter
· 3 min read
Provider
Provider là giải pháp quản lý state đơn giản và mạnh mẽ được Flutter team khuyên dùng.
Cài đặt Provider
dependencies:
provider: ^6.0.0
Ví dụ Cơ bản với Provider
// Model
class Counter with ChangeNotifier {
int _count = 0;
int get count => _count;
void increment() {
_count++;
notifyListeners();
}
}
// Widget sử dụng Provider
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider(
create: (_) => Counter(),
child: Consumer<Counter>(
builder: (context, counter, child) => Text('${counter.count}'),
),
);
}
}
Bloc (Business Logic Component)
Bloc là pattern giúp tách biệt business logic khỏi presentation layer.
Cài đặt Bloc
dependencies:
flutter_bloc: ^8.0.0
Ví dụ với Bloc
// Events
abstract class CounterEvent {}
class IncrementEvent extends CounterEvent {}
// State
class CounterState {
final int count;
CounterState(this.count);
}
// Bloc
class CounterBloc extends Bloc<CounterEvent, CounterState> {
CounterBloc() : super(CounterState(0)) {
on<IncrementEvent>((event, emit) {
emit(CounterState(state.count + 1));
});
}
}
GetX
GetX là giải pháp all-in-one cho state management, routing và dependency injection.
Cài đặt GetX
dependencies:
get: ^4.6.0
Ví dụ với GetX
// Controller
class CounterController extends GetxController {
var count = 0.obs;
void increment() => count++;
}
// Widget
class CounterWidget extends StatelessWidget {
final controller = Get.put(CounterController());
@override
Widget build(BuildContext context) {
return Obx(() => Text('${controller.count}'));
}
}
Riverpod
Riverpod là phiên bản cải tiến của Provider, khắc phục một số hạn chế.
Cài đặt Riverpod
dependencies:
flutter_riverpod: ^2.0.0
Ví dụ với Riverpod
// Provider definition
final counterProvider = StateNotifierProvider<Counter, int>((ref) => Counter());
class Counter extends StateNotifier<int> {
Counter() : super(0);
void increment() => state++;
}
// Widget
class CounterWidget extends ConsumerWidget {
@override
Widget build(BuildContext context, WidgetRef ref) {
final count = ref.watch(counterProvider);
return Text('$count');
}
}
So Sánh Các Giải Pháp
Provider
- Ưu điểm: Đơn giản, dễ học, được Flutter team khuyên dùng
- Nhược điểm: Có thể phức tạp khi ứng dụng lớn
Bloc
- Ưu điểm: Mạnh mẽ, có thể mở rộng, dễ test
- Nhược điểm: Có learning curve cao, nhiều boilerplate code
GetX
- Ưu điểm: All-in-one solution, ít code
- Nhược điểm: Có thể làm code khó maintain nếu không cẩn thận
Riverpod
- Ưu điểm: Type-safe, compile-time safety
- Nhược điểm: Khái niệm mới cần thời gian làm quen
Khi Nào Sử Dụng Gì?
- Provider: Cho dự án nhỏ và vừa, team mới học Flutter
- Bloc: Cho dự án lớn, cần tách biệt business logic rõ ràng
- GetX: Cho dự án cần phát triển nhanh, ít người
- Riverpod: Cho dự án cần type-safety cao, muốn tránh runtime errors