Design Patterns
1. MVC
1. Model
The Model represents the data and the business logic. It defines how data is managed and
class CounterModel {
  int _count = 0; // Private variable to store the count
    int get count => _count; // Getter to access the count
    void increment() {
      _count++; // Increments the count by 1
    }
}
        Purpose:
            o Encapsulates the logic for managing the counter value.
            o The _count variable is private, ensuring it can only be modified through
               defined methods (increment).
2. View
The View is responsible for the UI. It displays data from the model and forwards user
interactions to the controller.
class CounterView extends StatelessWidget {
  final CounterModel model; // Instance of the model
  final VoidCallback onIncrement; // Callback for the increment action
  CounterView({required this.model, required this.onIncrement}); //
Constructor
  @override
  Widget build(BuildContext context) {
    return Scaffold(
       appBar: AppBar(title: Text('MVC Counter App')),
       body: Center(
          child: Text('Count: ${model.count}'), // Displays the current
count
       ),
       floatingActionButton: FloatingActionButton(
          onPressed: onIncrement, // Calls the increment function when
tapped
          tooltip: 'Increment',
              child: Icon(Icons.add),
           ),
         );
    }
}
          Purpose:
              o Displays the counter value (model.count).
              o Invokes the onIncrement callback when the floating action button is
                 pressed.
3. Controller
The Controller acts as the intermediary between the Model and the View. It updates the
Model based on user input and refreshes the View when necessary.
class CounterController {
  final CounterModel model = CounterModel(); // Initializes the model
    void incrementCounter() {
      model.increment(); // Updates the model by incrementing the count
    }
}
          Purpose:
              o Receives user input (e.g., a button press).
              o Modifies the model by calling its methods (e.g., increment).
2. MVP
1. Model
The Model contains the application’s data and logic, representing the domain or business
layer.
class User {
  String username;
  String password;
    User(this.username, this.password);
}
          Purpose:
              o Represents the data entity (e.g., a User).
              o Encapsulates the properties username and password.
2. View Interface
The View is responsible for the user interface (UI) and interacts with the user. In the
MVP pattern, the view doesn't directly contain any business logic. Instead, it
communicates with the Presenter through an interface.
abstract class LoginView {
  void showLoginSuccess(); // Called when login is successful
  void showLoginError();   // Called when login fails
}
        Purpose:
            o Defines the contract between the Presenter and the View.
            o Declares methods (showLoginSuccess and showLoginError) that the
               presenter can call to update the view.
3. Presenter
The Presenter acts as the middleman between the Model and the View. It handles the
logic, updates the Model, and communicates results to the View.
class LoginPresenter {
  final LoginView view; // A reference to the view interface
    LoginPresenter(this.view);
    void login(String username, String password) {
      // Imagine we have a model that validates the user
      if (username == 'user' && password == 'pass') {
        view.showLoginSuccess(); // Notify the view about the success
      } else {
        view.showLoginError(); // Notify the view about the error
      }
    }
}
        Purpose:
            o Logic: Validates the user’s credentials (in this case, hardcoded for
               simplicity).
            o Communication:
                   Calls view.showLoginSuccess() when the login succeeds.
                   Calls view.showLoginError() when the login fails.
3. MVVM
1. Model
The Model represents the application's data and logic.
class Todo {
  String title;
  bool isDone;
    Todo(this.title, {this.isDone = false});
}
        Purpose:
            o Defines the data structure for a "To-Do" item.
            o Each Todo has a title and a boolean flag (isDone) to indicate whether
               it’s completed.
2. ViewModel
The ViewModel acts as the intermediary between the View and the Model. It manages
the application's state and logic.
class TodoViewModel {
  final List<Todo> _todos = [];
  UnmodifiableListView<Todo> get todos => UnmodifiableListView(_todos);
  // StreamController for the list of todos
  final _todosStreamController =
StreamController<List<Todo>>.broadcast();
    Stream<List<Todo>> get todosStream => _todosStreamController.stream;
    void addTodo(Todo todo) {
      _todos.add(todo); // Add the new todo to the list
    _todosStreamController.add(_todos); // Update the stream with the
new list
  }
}
        Purpose:
            o Maintains the list of Todo items in _todos.
            o Exposes the list as an immutable view using UnmodifiableListView.
            o Uses a StreamController to notify the View whenever the list changes.
        Key Points:
            o todosStream: Provides a real-time stream of updates to the View.
            o addTodo: Adds a new Todo to the list and updates the stream.
3. View
The View is responsible for the user interface (UI). It listens to updates from the
ViewModel and renders the data accordingly.
class TodoView extends StatelessWidget {
  final TodoViewModel viewModel;
  TodoView({required this.viewModel});
  @override
  Widget build(BuildContext context) {
    return StreamBuilder<List<Todo>>(
      stream: viewModel.todosStream, // Listen to the stream from the
ViewModel
      builder: (context, snapshot) {
        if (!snapshot.hasData) return CircularProgressIndicator(); //
Show a loader if data isn't available
            var todos = snapshot.data!;
            return ListView.builder(
               itemCount: todos.length,
               itemBuilder: (context, index) {
                  var todo = todos[index];
                  return ListTile(
                     title: Text(todo.title),
                     leading: Checkbox(
                        value: todo.isDone,
                        onChanged: (bool? value) {
                           // Update the todo
                        },
                     ),
                  );
               },
            );
         },
       );
  }
}
       Purpose:
           o Subscribes to the todosStream from the ViewModel using
              StreamBuilder.
           o Renders a ListView of Todo items based on the data provided by the
              ViewModel.
           o Uses a Checkbox to toggle the completion status of each Todo.
                 MVC            MVP (Model-        MVVM (Model-          Clean Architecture
                 (Model-        View-              View-ViewModel)
                 View-          Presenter)
                 Controller)
Structure        Divided into   Divided into       Divided into          Divided into
                 Model,         Model, View,       Model, View, and      Presentation,
                 View, and      and Presenter.     ViewModel.            Domain, and Data
                 Controller.                                             layers.
Responsibility   Controller     Presenter          ViewModel             Layers have distinct
                 handles        bridges            exposes state for     responsibilities: UI
                 input,         communication      View to listen to     (Presentation),
                 updates        between View       and react to          Business Logic
                 Model, and     and Model.         changes.              (Domain), and Data
                 notifies                                                Handling (Data).
                 View.
Coupling         Tightly        Tightly coupled    Loosely coupled:      Highly decoupled:
                 coupled        between View       View listens to       Independent layers
                 between        and Presenter.     ViewModel using       interact only via
                 View and                          reactive streams.     well-defined
                 Controller.                                             interfaces.
Data Binding     No data        No data            Supports              Not specific to data
                 binding        binding            automatic data        binding but allows
                 (View          (Presenter         binding using state   separation of state
                 manually       updates View).     management            handling.
                 updated).                         solutions.
Testability      Limited due    Better             High testability;     High testability; each
                 to coupling    testability;       ViewModel is          layer is independent
                 of View and    Presenter can be   isolated and easily   and testable.
                 Controller.    unit-tested.       testable.
View’s Role      Handles user   Passive;           Reactive; observes    Handles UI
              input and       delegates logic    ViewModel for          interaction and
              displays        to Presenter.      state updates.         delegates logic to
              output.                                                   Domain Layer.
Logic         Controller      Presenter          ViewModel              Domain Layer (Use
Location      contains        contains           contains state and     Cases) contains core
              business        business logic     logic but exposes it   business logic.
              logic and       and manages        reactively.
              updates         View updates.
              Model and
              View.
Interaction   View ↔          View ↔             View ↔                 Presentation Layer
Flow          Controller ↔    Presenter ↔        ViewModel ↔            ↔ Domain Layer ↔
              Model.          Model.             Model.                 Data Layer.
Focus         Handles UI      Ensures View       Decouples UI from      Separates concerns
              interactions    and Model stay     logic; state flows     into layers to make
              directly in     separate through   from ViewModel to      the app modular and
              Controller.     Presenter.         View.                  scalable.
Use Cases     Small apps      Medium             Reactive/scalable      Complex/scalable
              or legacy       complexity         apps: E.g., real-      systems: E.g.,
              systems:        apps: E.g., a      time chat apps or      enterprise apps or
              E.g., simple    form-based         dashboards.            apps requiring strict
              web apps like   mobile app.                               modularity.
              Rails.