Orientação gerada a partir de informações públicas. Apenas para referência.
O pacote lifecycle oferece uma maneira simples de adicionar ganchos para eventos do ciclo de vida do widget no Flutter, permitindo que os desenvolvedores executem código em estágios específicos, como inicialização, descarte e reconstrução. Ele aprimora a gestão de estado ao fornecer callbacks de ciclo de vida declarativos e limpos, sem exigir boilerplate complexo. Ideal para gerenciar efeitos colaterais, assinaturas ou tarefas de limpeza associadas à presença do widget na árvore da interface. O pacote suporta todas as principais plataformas, incluindo Android, iOS, Web, macOS, Windows e Linux.
Casos de uso
Gerenciando assinaturas durante o ciclo de vida do widget
Executar código na criação e destruição do widget
Gerenciando efeitos colaterais em widgets com estado
Simplificando a lógica de limpeza
Integração com gerenciamento de estado reativo
Evitando vazamentos de memória
Principais recursos
ganchos de ciclo de vida declarativos
Boilerplate mínimo
Suporte multiplataforma
Integração fácil com widgets existentes
Suporta eventos de init, dispose e rebuild
Leve e sem dependências
Indicado para
Desenvolvedores usando widgets com estado
Equipes adotando padrões funcionais do Flutter
Projetos que precisam de controle granular do ciclo de vida
Pessoas procurando alternativas para StatefulWidget
Aplicativos com criação/destruição frequente de widgets
Construtores focados em código limpo e sustentável
Considerações
Não necessário para widgets simples
Pode introduzir sobrecarga em atualizações de widget de alta frequência
Requer conhecimento sobre o ciclo de vida do widget do Flutter
Limitado a casos de uso específicos do ciclo de vida
Não substitui soluções completas de gerenciamento de estado
Melhor usado junto com outras abordagens de gerenciamento de estado
README original
Snapshot do README original do repositório-fonte vinculado. Consulte o repositório para o conteúdo mais recente.
lifecycle combines app state, Navigator routes, paged containers, and scroll
viewports into one immutable LifecycleSnapshot. A descendant can only be
active when every containing scope is active:
There is no global observer and no event bus. Each Navigator owns an explicit
controller, nested scopes compose automatically, and callbacks receive both
the resulting snapshot and the cause of the transition.
Phases are detached, hidden, visible, active, and disposed. A single
phase is the single source of truth; attached, visible, and active are
derived getters. A single state change produces events in deterministic order:
created → appeared → activated → deactivated → disappeared → disposed
Only events that apply to a transition are emitted. For example, hiding an
active widget emits deactivated and then disappeared.
LifecycleTransition.cause identifies whether the change came from the app,
a route, a back gesture, page selection, a viewport, the widget tree, or a
custom boundary.
Installation
dependencies:lifecycle:^1.0.0
import'package:lifecycle/lifecycle.dart';
App and Navigator setup
Create one NavigatorLifecycleController per Navigator. The controller owns
its observer; dispose the controller where you create it.
Use a separate controller, observer, and scope for each nested Navigator. Both
imperative routes and the Navigator pages API are supported. Opaque routes
hide the route below; non-opaque routes such as dialogs keep it visible but
inactive. Interactive back gestures expose the previous route as visible.
Routes can also be inspected or removed through the controller:
final route = navigation.routeNamed('/checkout');
final routes = navigation.routes;
if (route != null) {
final lifecycle = navigation.lifecycleFor(route);
debugPrint('checkout: ${lifecycle?.phase}');
navigation.removeRoute(route);
}
Use LifecycleBoundary to compose domain state with the surrounding scope.
It can restrict a descendant, but it cannot make a descendant more active than
its parent.
LifecyclePageView owns page scopes and forwards the usual PageView options.
The selected page becomes active only after scrolling settles. During a drag,
visible pages expose a fractional visibility and remain inactive.
The widget deliberately does not change Flutter's keep-alive policy. A lazy
page that is disposed emits disposed; wrap page content with
AutomaticKeepAliveClientMixin when its State must survive off-screen.
LifecycleTabBarView follows both animated taps and horizontal swipes. A tab
is active only when the TabController is settled.
ListView, GridView, and CustomScrollView
Place ViewportLifecycleItem below the nearest Scrollable. Visibility is
calculated from the item's two-dimensional area inside that viewport, so
vertical lists, horizontal lists, grids, and slivers share the same behavior.
An item is visible when its fraction reaches visibleThreshold. By default it
can become active only after scrolling settles and its fraction reaches
activeThreshold; use ViewportLifecycleActivationPolicy.immediate to retain
activation while scrolling. If activeThreshold is omitted, it uses the
visible threshold. Reported fractions are stabilized to one-percent increments
by default; set visibleFractionGranularity to zero for exact measurements.
The containing app, route, and page states still apply.
Direct controller use
Most apps only need widgets, but LifecycleController is public for custom
containers. Child state is composed with its parent, listeners are safe to
add/remove during delivery, and reentrant updates are queued deterministically.
final parent = LifecycleController()..attach();
final child = LifecycleController(
constraint: constLifecycleConstraint.hidden(),
);
voidonChildChanged() {
final transition = child.lastTransition!;
debugPrint('${transition.previous.phase} -> ${transition.current.phase}');
}
child
..addListener(onChildChanged)
..attach(parent: parent);
child.updateLocal(
constraint: constLifecycleConstraint.active(),
cause: LifecycleCause.custom,
);
final subtree = LifecycleScope(
controller: child,
child: constCustomContainerContent(),
);
LifecycleController uses the standard ChangeNotifier channel for both
snapshot and transition changes. During a listener callback, value is the
latest snapshot and lastTransition describes the atomic change that produced
it. Remember to call removeListener when the listener can outlive the
controller.
See the example application
and the tests for complete runnable compositions.
1.0 migration
Version 1.0 is a deliberate API redesign. The global
defaultLifecycleObserver, legacy wrapper classes, and dispatch/subscribe
mixins were removed. Replace them with explicit LifecycleApp and
NavigatorLifecycleController setup, then use LifecycleListener,
LifecycleStateMixin, LifecyclePageView, LifecycleTabBarView, and
ViewportLifecycleItem.