Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 73 ยท State management

Choosing State Management and App Architecture

Choose a Flutter state management approach and structure your app in layers: MVVM, the repository pattern, dependency injection with get_it, and a comparison.

You have now seen setState, ValueNotifier, Provider, Riverpod and BLoC. A question remains that no package answers for you: how should the whole app be organized? Which code talks to the server? Where do rules like "a coupon cannot be used twice" live? How do you swap a real API for a fake one in a test?

This lesson gives you a simple layered architecture that works with any of the state tools, shows the repository pattern and dependency injection, and ends with a decision matrix.

Real vs stand-in. The Dart is real Flutter code, read-only here. The JavaScript stand-ins show the layering and a small service locator, which behave the same in any language.

Three layers

UI Widgets. Draw state, send actions.
Logic ViewModels, Cubits, notifiers.
Data Repositories, APIs, databases.

Dependencies point downwards only.

1 / 2

The layers

flowchart TD
    UI["UI layer<br/>widgets"] --> VM["Logic layer<br/>ViewModel / Cubit / Notifier"]
    VM --> Repo["Data layer<br/>repositories"]
    Repo --> Remote["Remote source<br/>REST API"]
    Repo --> Local["Local source<br/>database"]

Each layer knows only about the one directly below it.

  • UI layer. Widgets. They show the current state and call methods on the logic layer. They contain no networking and no business rules.
  • Logic layer (presentation logic). Holds screen state, turns user actions into repository calls and results into UI state. In MVVM this is the ViewModel; in BLoC it is a Cubit or Bloc; in Riverpod a Notifier.
  • Data layer. Repositories hide where data comes from. They combine a remote source (HTTP) and a local source (cache, database) and return domain models, not raw JSON.

A simple folder layout:

TEXT
lib/
  main.dart
  ui/
    products/
      products_screen.dart
      products_view_model.dart
  data/
    repositories/
      product_repository.dart
    services/
      api_client.dart
  domain/
    models/
      product.dart

Organizing by feature (products/, cart/, profile/) usually scales better than by type (widgets/, models/). Pick one and be consistent.

MVVM in Flutter

Model, View, ViewModel: the View is a widget, the Model is data, and the ViewModel is a ChangeNotifier that exposes screen state and commands.

DART
class ProductsViewModel extends ChangeNotifier {
  ProductsViewModel(this._repository);

  final ProductRepository _repository;

  List<Product> _products = const [];
  bool _loading = false;
  String? _error;

  List<Product> get products => _products;
  bool get loading => _loading;
  String? get error => _error;

  Future<void> load() async {
    _loading = true;
    _error = null;
    notifyListeners();
    try {
      _products = await _repository.fetchProducts();
    } catch (_) {
      _error = 'Could not load products';
    } finally {
      _loading = false;
      notifyListeners();
    }
  }
}

The widget listens with ListenableBuilder, Provider or any other tool from the previous lessons; the ViewModel does not care which. That is the point: the architecture is independent of the state package. A Cubit, a Riverpod AsyncNotifier and this ViewModel all play the same role.

The repository pattern

A repository is the single door to one kind of data. The logic layer asks it for products and never learns whether they came from the network or a cache:

DART
abstract interface class ProductRepository {
  Future<List<Product>> fetchProducts();
}

class ApiProductRepository implements ProductRepository {
  ApiProductRepository(this._api, this._cache);

  final ApiClient _api;
  final ProductCache _cache;

  @override
  Future<List<Product>> fetchProducts() async {
    try {
      final json = await _api.get('/products');
      final products = [for (final j in json) Product.fromJson(j)];
      await _cache.save(products);
      return products;
    } on SocketException {
      return _cache.load();          // offline: fall back to the cache
    }
  }
}

The abstract interface is what tests and ViewModels depend on. A FakeProductRepository returns fixed lists. Raw JSON, status codes and exceptions stay inside the repository; see HTTP requests and JSON for the networking details.

Stand-in: layers with a fake and a real source

JS UI, ViewModel and repository, with a swappable data source

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The same ViewModel and the same render function work with a real repository, a failing one and a fake. Only the data layer changed.

Dependency injection with get_it

Somebody has to create the ApiClient, the repository and the ViewModel and connect them. Dependency injection means objects receive their dependencies instead of building them. Provider and Riverpod already do this inside the widget tree. Outside it, a popular choice is the get_it service locator:

DART
import 'package:get_it/get_it.dart';

final getIt = GetIt.instance;

void setupDependencies() {
  getIt.registerLazySingleton<ApiClient>(() => ApiClient(baseUrl: apiUrl));
  getIt.registerLazySingleton<ProductRepository>(
    () => ApiProductRepository(getIt<ApiClient>(), ProductCache()),
  );
  getIt.registerFactory<ProductsViewModel>(
    () => ProductsViewModel(getIt<ProductRepository>()),
  );
}

void main() {
  setupDependencies();
  runApp(const MyApp());
}

Three registration kinds cover most needs:

  • registerSingleton: you create the object now; everyone shares it.
  • registerLazySingleton: created on first use, then shared (repositories, API clients).
  • registerFactory: a new instance on every getIt<T>() call (ViewModels that belong to one screen).

In tests, register fakes instead: getIt.registerLazySingleton<ProductRepository>(() => FakeProductRepository()), and call getIt.reset() in tearDown.

A word of caution: call getIt<T>() only at the edges (where you wire things together, or in a screen's initState). If every class reaches into the locator itself, dependencies become hidden. Prefer constructor injection, as in ProductsViewModel(this._repository), so the code reveals what it needs.

Stand-in: a tiny service locator

JS Lazy singleton versus factory

Press Run (or Ctrl + Enter) to see the console output here.

No output.

GetX, MobX and other options

Besides Provider, Riverpod and BLoC, you will meet other packages in tutorials and job listings. Know what they are so you can judge them.

GetX bundles state management, navigation and dependency injection into one package with very little code:

DART
class CounterController extends GetxController {
  final count = 0.obs;                 // an observable (Rx) value
  void increment() => count.value++;
}

class CounterPage extends StatelessWidget {
  const CounterPage({super.key});

  @override
  Widget build(BuildContext context) {
    final c = Get.put(CounterController());          // register and fetch
    return Scaffold(
      body: Center(child: Obx(() => Text('${c.count}'))),   // rebuilds when count changes
      floatingActionButton: FloatingActionButton(onPressed: c.increment, child: const Icon(Icons.add)),
    );
  }
}
// GetMaterialApp and Get.to(NextPage()) replace MaterialApp and Navigator.

It is quick to start, but it relies on global state and its own navigation layer, which makes testing and large teams harder, and its maintenance activity has varied over time. Check recent releases on pub.dev before adopting it in a long-lived app.

MobX brings the observable/reaction model from JavaScript. You declare @observable fields, @action methods and @computed values in a store class, run build_runner to generate the glue, and wrap widgets in Observer. It suits teams that already know MobX and accept code generation.

Signals (the signals_flutter package) use fine-grained reactivity: final count = signal(0), computed(() => count.value * 2), and a Watch widget that rebuilds only where a signal is read. It resembles the stand-in below. Redux (flutter_redux) keeps one store updated by reducers, and is rarely chosen for new apps because BLoC and Riverpod give similar guarantees with less boilerplate. The built-in ValueNotifier and ListenableBuilder already cover many small cases (lifting state up).

Their common idea is automatic dependency tracking: a reaction records which observables it read, and re-runs only when one of them changes.

JS Observable, computed and reaction in 30 lines

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Comparison matrix

Approach Boilerplate Learning curve Async support Testing Best for
setState Very low Very low Manual Widget tests Local, ephemeral state
ValueNotifier / ChangeNotifier Low Low Manual Easy (plain Dart) Small apps, simple models
Provider Low Low FutureProvider, manual Good Small to medium apps, teams new to Flutter
Riverpod Medium Medium Built in (AsyncValue) Excellent (overrides) Apps with lots of async data and dependencies
BLoC / Cubit Higher Medium to high Streams Excellent (bloc_test) Large teams, strict flows, audit trails

There is no single winner. A few honest rules of thumb:

  1. Start with the simplest thing that works. Local state in a StatefulWidget is fine until two distant widgets need it.
  2. Pick one app-wide solution and use it everywhere. Mixing four libraries in one app is harder to maintain than any single one of them.
  3. Match the team. The best choice is the one your team understands and can review.
  4. Separate layers regardless of the tool. Repositories and models outlive any state package; you can change the logic layer later without touching the data layer.
  5. Avoid putting everything in global state. Keep screen-specific state local or auto-disposed.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which layer should contain the HTTP calls?

    Networking belongs in the data layer so the UI and logic layers stay testable and independent of where data comes from.
  2. 2. What is the benefit of depending on an abstract ProductRepository instead of the concrete class?

    Depending on an interface lets you replace the implementation, for tests or for a different data source.
  3. 3. Which get_it registration creates a new object on every request?

    registerFactory builds a fresh instance each time, which suits per-screen ViewModels. The singleton variants share one instance.
  4. 4. A teammate says the architecture depends on choosing Riverpod over Provider. What is the best response?

    UI, logic and data layers are independent of the package used inside the logic layer.

Summary

  • Organize code into UI, logic and data layers, with dependencies pointing downward.
  • A ViewModel (or Cubit, or Notifier) holds screen state; a repository hides where data comes from and returns domain models.
  • Constructor injection reveals dependencies; get_it wires them at the edges with singleton, lazy singleton and factory registrations.
  • Choose the simplest state tool that fits the team and the app, use it consistently, and keep the layers regardless.

Next: HTTP Requests and JSON