• Flutter
  • State Management
  • Design Patterns
  • Mobile Development
  • Technical Debt

Flutter Design Patterns That Actually Scale

Avoid common Flutter state management anti-patterns like global mutable state and deeply nested notifiers. Learn design patterns for scalable Flutter apps.

Flutter Design Patterns That Actually Scale

Avoiding Global Mutable State Objects

A single global controller or mutable singleton becomes an implicit dependency for unrelated screens. Any mutation can trigger broad rebuilds or produce stale reads. Tests must reset global state between cases, and lifecycle ownership becomes unclear. Multiple screens can write the same value, creating last-write-wins behavior without an explicit transition model.

Text
// Before
class AppState {
  static final AppState instance = AppState._();
  AppState._();

  User? user;
  List<CartItem> cart = [];
}

// Any widget can mutate shared state.
AppState.instance.cart.add(item);
Text
// After
class CartState {
  final List<CartItem> items;

  const CartState({this.items = const []});

  CartState add(CartItem item) =>
      CartState(items: [...items, item]);
}

class CartViewModel extends ChangeNotifier {
  CartState _state = const CartState();

  CartState get state => _state;

  void addItem(CartItem item) {
    _state = _state.add(item);
    notifyListeners();
  }
}

Use local state for a single widget or screen. Lift state only to the nearest common ancestor that needs it. Use a view model, notifier, or equivalent scoped state object for shared feature state. Keep mutation methods narrow and explicit.

Flutter's official architecture guidance, as of May 2026, recommends separating applications into a UI layer and a data layer. Repositories act as the source of truth for model data, while view models expose UI-ready state.

Implementing Unidirectional Data Flow

Flutter architectural guidance from May 2026 recommends unidirectional data flow: state moves from the data layer through the logic layer to widgets, rather than widgets directly mutating shared data. When widgets can write directly to a repository or global object, you lose the ability to trace which events caused a state change.

Duplicating the same data across layers creates synchronization failures. A screen keeps its own copy of a user, order, or cart while a repository or cache keeps another copy. Updates must manually synchronize every copy. One screen can display stale data after another screen changes the underlying record.

Text
// Before
class ProfilePageState extends State<ProfilePage> {
  User? user;

  Future<void> load() async {
    user = await api.fetchUser();
    setState(() {});
  }
}

A separate repository may independently cache the same user, creating two authorities.

Text
// After
class UserRepository {
  User? _cachedUser;

  Future<User> getUser() async {
    return _cachedUser ??= await api.fetchUser();
  }

  Future<User> updateUser(User user) async {
    final saved = await api.updateUser(user);
    _cachedUser = saved;
    return saved;
  }
}

The view model consumes repository output rather than creating a second authoritative copy:

Text
class ProfileViewModel extends ChangeNotifier {
  ProfileViewModel(this.repository);

  final UserRepository repository;
  User? user;
  bool isLoading = false;
  Object? error;

  Future<void> load() async {
    isLoading = true;
    error = null;
    notifyListeners();

    try {
      user = await repository.getUser();
    } catch (exception) {
      error = exception;
    } finally {
      isLoading = false;
      notifyListeners();
    }
  }
}

Flutter architectural guidance from May 2026 says that app data types should have a single source of truth and that the source-of-truth class should be the only class that modifies it. Widgets read from view models, view models read from repositories, and repositories own the canonical copy.

Ensuring Immutability of State Data

In-place mutation of collections or objects prevents you from observing what changed. A list modified by add() or remove() does not produce a new reference, so comparison-based rebuild logic cannot detect the change. Immutable state makes transitions observable and prevents callers from modifying repository-owned collections without going through an explicit command.

Text
class ProfileState {
  const ProfileState({
    this.name = '',
    this.isSaving = false,
    this.error,
  });

  final String name;
  final bool isSaving;
  final Object? error;

  ProfileState copyWith({
    String? name,
    bool? isSaving,
    Object? error,
  }) {
    return ProfileState(
      name: name ?? this.name,
      isSaving: isSaving ?? this.isSaving,
      error: error,
    );
  }
}

Avoid:

Text
state.items.add(item);
notifyListeners();

Prefer:

Text
state = state.copyWith(
  items: [...state.items, item],
);
notifyListeners();

Flutter architectural guidance from May 2026 states that data should be immutable and persistent, reducing accidental mutations and making state transitions easier to reason about and test. When every state change produces a new object, you can log transitions, replay sequences, and write snapshot tests without side effects.

Separating UI from Business Logic and Data

Event logic directly embedded in widgets makes widgets responsible for validation, API calls, caching, navigation, error mapping, and state mutation. The same business rule is copied across screens. Unit testing requires constructing widget trees instead of testing a small domain object.

Text
// Before
onPressed: () async {
  if (emailController.text.isEmpty) return;

  setState(() => saving = true);

  try {
    await api.save(emailController.text);
    if (context.mounted) {
      Navigator.pushNamed(context, '/success');
    }
  } catch (_) {
    setState(() => error = 'Could not save');
  }
}
Text
// After
class SignupViewModel extends ChangeNotifier {
  SignupViewModel(this.repository);

  final SignupRepository repository;
  AsyncState<void> state = const Initial();

  Future<bool> submit(String email) async {
    state = const Loading();
    notifyListeners();

    try {
      await repository.signup(email);
      state = const Success(null);
      notifyListeners();
      return true;
    } catch (error) {
      state = Failure(error);
      notifyListeners();
      return false;
    }
  }
}

The widget renders state and delegates the command:

Text
final submitted = await viewModel.submit(email);
if (submitted && context.mounted) {
  context.go('/success');
}

Passing BuildContext into repositories or services couples data and business layers to the widget tree. Background operations may use a context after its widget has been disposed. Services become difficult to test without Flutter bindings. Navigation and presentation decisions leak into data-access code.

Text
// Before
class OrderService {
  Future<void> placeOrder(BuildContext context) async {
    await api.placeOrder();
    Navigator.of(context).pushNamed('/confirmation');
  }
}
Text
// After
class OrderRepository {
  Future<void> placeOrder() => api.placeOrder();
}

class OrderViewModel extends ChangeNotifier {
  OrderViewModel(this.repository);

  final OrderRepository repository;

  Future<void> placeOrder() async {
    await repository.placeOrder();
  }
}

The UI decides how to respond:

Text
await viewModel.placeOrder();

if (context.mounted) {
  context.go('/confirmation');
}

Flutter's current application-architecture guidance from May 2026 identifies repositories as the appropriate location for data loading, refreshing, polling, caching, and transformation into domain models. View models sit between repositories and widgets, exposing UI-ready state and handling user commands.

Handling Asynchronous Operations Gracefully

Calling APIs inside build() causes duplicate network calls, repeated parsing, loading flicker, race conditions, and unnecessary battery or bandwidth use. build() can run many times. Starting a request from build() can overwrite local state or restart asynchronous work. Rebuilding the widget can trigger a new request before the previous one completes.

Text
// Before
@override
Widget build(BuildContext context) {
  return FutureBuilder(
    future: api.fetchProducts(), // New Future may be created on every build.
    builder: ...
  );
}
Text
// After
late final Future<List<Product>> productsFuture;

@override
void initState() {
  super.initState();
  productsFuture = api.fetchProducts();
}

@override
Widget build(BuildContext context) {
  return FutureBuilder<List<Product>>(
    future: productsFuture,
    builder: (context, snapshot) {
      if (snapshot.connectionState == ConnectionState.waiting) {
        return const CircularProgressIndicator();
      }
      if (snapshot.hasError) {
        return ErrorView(onRetry: _reload);
      }
      return ProductList(products: snapshot.data!);
    },
  );
}

For larger features, move the request and loading state into a repository and view model. Flutter's architectural overview from November 2026 notes that Flutter may call build() repeatedly and recommends that build methods return quickly; heavy computation should run asynchronously and be stored as state.

Treating loading and errors as booleans permits impossible combinations such as isLoading == true and error != null. A previous error can remain visible after a successful retry. Empty, stale, partial, and refreshed data cannot be distinguished.

Text
// Before
bool isLoading = false;
bool hasError = false;
List<Product> products = [];
Text
// After
sealed class AsyncState<T> {
  const AsyncState();
}

class Initial<T> extends AsyncState<T> {
  const Initial();
}

class Loading<T> extends AsyncState<T> {
  const Loading({this.previous});

  final T? previous;
}

class Success<T> extends AsyncState<T> {
  const Success(this.value);

  final T value;
}

class Failure<T> extends AsyncState<T> {
  const Failure(this.error, {this.previous});

  final Object error;
  final T? previous;
}

This makes permitted UI states explicit and supports stale-while-refreshing behavior without conflating "no data," "loading," and "failed." At minimum, distinguish initial or unrequested, loading without prior data, loading with prior data, successful data, empty successful data, failure without prior data, and failure with stale prior data.

Make commands idempotent or guard concurrent execution:

Text
bool _submitting = false;

Future<void> submit() async {
  if (_submitting) return;

  _submitting = true;
  notifyListeners();

  try {
    await repository.submit();
  } finally {
    _submitting = false;
    notifyListeners();
  }
}

For search or type-ahead, debounce input, cancel or ignore obsolete requests, associate responses with a request identifier, and apply a response only if it belongs to the latest request:

Text
int _requestId = 0;

Future<void> search(String query) async {
  final request = ++_requestId;
  final results = await repository.search(query);

  if (request != _requestId) return;
  state = state.copyWith(results: results);
  notifyListeners();
}

Managing Navigation and Routing Effectively

Using navigation as state management treats a route stack as the source of truth for authentication, onboarding, permissions, or selected entities. Back-stack manipulation becomes a substitute for explicit state transitions. Deep links and cold starts produce inconsistent screens because navigation history differs from application state.

Text
// Before
if (loggedIn) {
  Navigator.pushReplacementNamed(context, '/home');
} else {
  Navigator.pushReplacementNamed(context, '/login');
}

Scattered redirects across buttons, API callbacks, and lifecycle methods can create competing navigation decisions.

Text
// After
GoRouter(
  refreshListenable: authViewModel,
  redirect: (context, state) {
    final isLogin = state.matchedLocation == '/login';

    if (!authViewModel.isInitialized) return '/splash';
    if (!authViewModel.isAuthenticated && !isLogin) return '/login';
    if (authViewModel.isAuthenticated && isLogin) return '/home';

    return null;
  },
  routes: [
    GoRoute(path: '/login', builder: (_, __) => const LoginPage()),
    GoRoute(path: '/home', builder: (_, __) => const HomePage()),
  ],
);

Flutter's current architecture recommendations from March 2026 recommend go_router for declarative navigation, deep linking, and web support, while reserving the built-in Navigator for short-lived, non-deep-linkable screens. Use declarative route configuration for app-level navigation decisions and imperative Navigator calls for transient flows such as dialogs or temporary screens.

A provider, listener, or notifier placed above the entire application causes minor changes to rebuild large portions of the widget tree even when only a small subtree depends on it. Rebuild cost and dependency relationships become difficult to inspect.

Text
// Before
ListenableBuilder(
  listenable: appViewModel,
  builder: (_, __) => EntireApplication(appViewModel),
);
Text
// After
Column(
  children: [
    const StaticHeader(),
    ListenableBuilder(
      listenable: cartViewModel,
      builder: (_, __) => CartBadge(count: cartViewModel.count),
    ),
    const ProductGrid(),
  ],
);

Flutter reconstructs affected widget portions by invoking build() when state changes; keeping listeners close to the widgets that need them limits unnecessary work. Establish a state ownership matrix: text field, tab index, animation, and expanded panel state belong to the widget or local controller using State, ValueNotifier, or ValueListenableBuilder. State shared by sibling widgets belongs to the nearest common ancestor or scoped feature model using constructor parameters, ChangeNotifier, or an equivalent scoped notifier. Screen request state belongs to a view model or controller using an immutable state object with loading, success, and failure variants. Cached server data belongs to a repository. Authentication and session state belong to an app-scoped session repository or auth model with declarative route refresh and redirect. One-off UI events use an explicit event channel or consumable effect for snack bars, dialogs, or navigation effects handled by the UI. Database or API access belongs to a data source behind a repository, with repository methods returning domain models.

Use a consistent feature structure:

Text
lib/
  core/
    errors/
    networking/
    routing/
  features/
    orders/
      data/
        order_api.dart
        order_repository.dart
      domain/
        order.dart
      presentation/
        order_page.dart
        order_view_model.dart
        order_state.dart

Recommended dependency direction: Widget → ViewModel → Repository → Data source. Avoid reverse dependencies such as repositories importing widgets or APIs returning presentation-specific objects.

Duplicated state and scattered mutations create synchronization paths that are hard to enumerate. Each additional writer increases the number of possible update sequences. Requests initiated from build() may be recreated during rebuilds, causing duplicate calls and repeated parsing, unnecessary API traffic, latency, battery consumption, and possible rate-limit exposure. Widget-heavy business logic requires UI setup for unit tests and increases the number of files touched for a change. Global mutable state and implicit dependencies make it difficult to identify which screens can observe or mutate a value, increasing review and debugging effort, particularly when lifecycle and disposal behavior are unclear. Boolean loading flags typically do not model cached data, refresh-in-place, retry, cancellation, or partial failure; teams often add ad hoc flags and conditional branches, increasing state-space complexity. Imperative route pushes distributed across the codebase can produce duplicate screens, broken back behavior, inconsistent cold-start handling, and deep-link failures. Repositories and view models with constructor-injected dependencies can be tested without rendering widgets. Multiple state-management mechanisms used without boundaries—such as local setState, global singletons, streams, providers, and ad hoc callbacks—force developers to learn different lifecycle and update semantics for each feature. Immutable state models and explicit state transitions make it easier to reproduce bugs from inputs and transitions.

If your codebase could use a second set of experienced eyes on architecture, state flow, or test coverage, that's exactly the kind of work Azguards does—let's talk.

Architect Your Solution → Explore our Platforms & Modernization work →