This repository demonstrates an efficient implementation of state management in Flutter using a service locator pattern with getIt. The primary goal is to achieve reactive code without resorting to imperative approaches like setState. The code is designed to observe changes only in the needed areas, eliminating the need to rebuilding unneccessary areas..
Special thanks to Ozkan Kaya for providing the insightful tutorial and code implementation on efficient state management using service locator in Flutter. This project drew inspiration and learning from his work.
- Setup
getIt: Initialize the service locatorgetItin themainfunction by callinginitGetIt(). - Widgets:
MyHomePage: Represents the main page of the app. It utilizesCounterStateandListViewStatefor managing state.CounterText: Widget responsible for displaying the current counter value.ListViewContainer: Widget for displaying a list of posts with add and remove functionality.
- State Management:
CounterState: Manages the counter state with methods for incrementing, decrementing, and resetting the counter.ListViewState: Manages the list of posts with methods for adding and removing posts.- Both
CounterStateandListViewStateutilizeValueNotifierto notify listeners of state changes.
- UI Components:
AlertDialog: Displays a warning when the counter reaches 10, prompting the user to continue or reset.AppBar: Customized app bar with an icon.FloatingActionButton: Allows adding new posts to the list.
- Reactive Code: Utilizes
ValueNotifierandValueListenableBuilderto achieve reactive behavior without relying onsetState. - Service Locator Pattern: Uses
getItfor efficient and centralized dependency management. - Separation of Concerns: State management logic is separated from UI components for better code organization and maintainability.
flutter/material.dart: Flutter framework for building UI.get_it: Package for implementing the service locator pattern.
- Clone the repository.
- Ensure Flutter SDK is installed and up-to-date.
- Run
flutter pub getto install dependencies. - Run the app on your preferred device or emulator.
Contributions are welcome! If you have suggestions for improvements or new features, feel free to open an issue or submit a pull request.