State Management
State Management ក្នុង Flutter
State Management គឺជា one of the most important concepts ក្នុង Flutter។ វាជួយគ្រប់គ្រង data (state) របស់ app និងធ្វើឱ្យ UI update នៅពេលដែល data ផ្លាស់ប្តូរ។
📚 អ្វីជា State?
State គឺជាទិន្នន័យដែលអាចផ្លាស់ប្តូរបាននៅពេល app កំពុងដំណើរការ។ ឧទាហរណ៍:
- User login status (បាន login ឬមិនទាន់)
- Shopping cart items (ផលិតផលក្នុង cart)
- Form input values (អត្ថបទក្នុង TextField)
- Theme mode (light/dark)
- Loading status (កំពុងទាញយកទិន្នន័យ)
🎯 ប្រភេទ State
1. Local State (Ephemeral State)
State ដែលប្រើក្នុង widget តែមួយ។ មិនចាំបាច់ share ជាមួយ widgets ផ្សេង។
- Selected tab index
- Current page in PageView
- Animation progress
Solution: StatefulWidget + setState()
2. App State (Shared State)
State ដែលត្រូវការ share រវាងច្រើន widgets ឬ screens។
- User profile information
- Shopping cart contents
- Notification settings
- Authentication status
Solutions: Provider, Riverpod, BLoC, GetX, Redux
⚠️ បញ្ហានៃ State Management
Prop Drilling Problem:
// មិនល្អ: ត្រូវបញ្ជូន data ឆ្លងកាត់ច្រើន widgets
HomePage(user: user)
└─ ProfileSection(user: user)
└─ UserInfo(user: user)
└─ UserName(user: user) // ត្រូវការ user ទើបបាន
Solution with Provider:
// ល្អ: widgets ណាត្រូវការ user អាចទទួលបានដោយផ្ទាល់
HomePage()
└─ ProfileSection()
└─ UserInfo()
└─ UserName() // Provider.of(context)
🔄 State Management Approaches
1. setState() - Built-in
Pros: ងាយស្រួល, មិនត្រូវការ package, ល្អសម្រាប់ local state
Cons: មិនល្អសម្រាប់ complex apps, hard to test
2. Provider - Recommended
Pros: ងាយរៀន, មាន performance ល្អ, recommended by Flutter team
Cons: Requires boilerplate code
3. Riverpod - Modern Provider
Pros: Compile-time safety, testing friendly, no BuildContext needed
Cons: ថ្មី, documentation មិនទាន់ច្រើន
4. BLoC - Business Logic Component
Pros: Separation of business logic, testable, predictable
Cons: Steep learning curve, verbose code
5. GetX - All-in-one
Pros: Easy syntax, includes routing & dependency injection
Cons: Not recommended by Flutter team, magic behavior
🔄 Provider Pattern
import 'package:provider/provider.dart';
class Counter extends ChangeNotifier {
int _count = 0;
int get count => _count;
void increment() {
_count++;
notifyListeners();
}
}
// Main app
void main() {
runApp(
ChangeNotifierProvider(
create: (context) => Counter(),
child: MyApp(),
),
);
}
// ប្រើ Provider
class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
final counter = Provider.of<Counter>(context);
return Text(counter.count.toString());
}
}
💡 ជំនួយ: Provider ងាយប្រើ និងពេញនិយម។