패키지, 저장소 및 앱 카테고리 검색

패키지 상세v2.5.0

watch_it

get_it로 구동되는 간단한 상태 관리입니다. get_it 서비스 로케이터 내의 객체 변경 사항을 감지하고 UI를 해당 내용에 따라 다시 렌더링할 수 있습니다.

AndroidiOSWebmacOSWindowsLinux
30일 다운로드
1.3만
좋아요
213
Pub 점수
160

패키지 설치

flutter pub add watch_it

패키지 개요

공개 정보를 바탕으로 생성한 선택 가이드입니다.

Watch It는 Flutter용 가벼운 상태 관리 솔루션으로, 등록된 객체의 변경 사항을 감지하고 이러한 변경이 발생할 때 자동으로 UI를 다시 렌더링하는 get_it 서비스 로케이터를 활용합니다. get_it와 원활하게 통합되어 복잡한 보일러플레이트나 추가 위젯 없이도 상태 업데이트를 간소화합니다. 서비스 객체와 연결된 반응형 동작이 필요한 앱에 적합하며, 수동 상태 처리를 줄여 깔끔하고 유지보수 쉬운 코드를 촉진합니다. 모든 주요 Flutter 플랫폼을 지원하며, 이미 get_it를 사용 중인 프로젝트에서도 잘 작동합니다.

사용 사례

  • 서비스 상태에 기반한 반응형 UI 업데이트
  • 작은에서 중간 규모의 앱에서 상태 관리 간소화
  • 의존성 주입 서비스의 변경 사항 관찰
  • 양식 또는 목록에서 실시간 데이터 동기화
  • 상태가 있는 위젯에서 반복 코드 줄이기

주요 기능

  • get_it 위에 구축됨
  • 객체 변경 시 자동 UI 재구성
  • 최소한의 설정 및 통합
  • 크로스 플랫폼 지원
  • 추가 상태 클래스 필요 없음
  • 경량이고 빠름

적합한 대상

  • get_it를 사용하는 개발자
  • 간단에서 중간 수준의 상태 요구 사항을 가진 프로젝트
  • 최소한의 상태 관리 오버헤드를 원하는 팀
  • 반응형 서비스 업데이트가 필요한 앱
  • Flutter 초보자가 상태 솔루션 탐색 중

고려 사항

  • 비복잡한 상태 시나리오에 가장 적합
  • Provider 또는 Bloc과 같은 완전한 상태 관리 솔루션을 대체하지 않습니다
  • 관찰 가능한 개체의 신중한 관리가 필요합니다
  • 전용 상태 라이브러리에 비해 디버깅 도구가 제한적
  • 복잡한 상태 로직을 가진 대규모 애플리케이션에는 적합하지 않음

원본 README

연결된 소스 저장소의 README 원문 스냅샷입니다. 최신 내용은 저장소에서 확인하세요.

watch_it logo
Buy Me A Coffee
Sponsor

watch_it codecov

📚 Complete documentation available at flutter-it.dev Check out the comprehensive docs with detailed guides, examples, and best practices!

The easiest state management for Flutter built on get_it

Widgets automatically rebuild when data changes. No ValueListenableBuilder, no StreamBuilder, no FutureBuilder—just watch your data and your UI stays in sync.

One line instead of 12. No nesting, no boilerplate. Watch multiple values without builder hell.

Part of flutter_it — A construction set of independent packages. watch_it + get_it is the recommended foundation. Add command_it and listen_it when you need them.

Why watch_it?

  • ✨ Zero Boilerplate — No Builders, no setState, no widget tree nesting
  • ⚡ Automatic Cleanup — Subscriptions disposed automatically when widget destroys
  • 🎯 Type Safe — Catch errors at compile time with generics
  • 🔧 Flexible Data Types — Works with Listenable, ValueListenable, Stream, Future
  • 📊 Multiple Watches — Watch 3+ values without pyramid of doom
  • 🧪 Test Friendly — Easy to mock and inject dependencies

Learn more about the benefits →

Quick Start

Installation

Add to your pubspec.yaml:

dependencies:
  watch_it: ^2.2.0
  get_it: ^9.0.5  # Recommended - watch_it builds on get_it
Basic Example
import 'package:watch_it/watch_it.dart';

// 1. Create a model with ValueNotifier properties
class CounterModel {
  final count = ValueNotifier<int>(0);
  void increment() => count.value++;
}

// 2. Register with get_it (using exported 'di' instance)
di.registerSingleton(CounterModel());

// 3. Watch it - widget rebuilds automatically
class CounterWidget extends WatchingWidget {
  @override
  Widget build(BuildContext context) {
    final count = watchValue((CounterModel m) => m.count);
    return Column(
      children: [
        Text('$count'),
        ElevatedButton(
          onPressed: di<CounterModel>().increment,
          child: Text('Increment'),
        ),
      ],
    );
  }
}

That's it! No builders, no manual subscriptions. Just watch and rebuild.

Multiple Watches

Watch multiple values without nesting builders:

class UserDashboard extends WatchingWidget {
  @override
  Widget build(BuildContext context) {
    // Watch multiple values - no nested builders!
    final userName = watchValue((UserModel m) => m.name);
    final isLoggedIn = watchValue((AuthModel m) => m.isLoggedIn);
    final notifications = watchStream(
      (NotificationModel m) => m.updates,
      initialValue: []
    );

    if (!isLoggedIn) return LoginScreen();

    return Text(
      '$userName - ${notifications.data?.length ?? 0} notifications'
    );
  }
}

Full tutorial

Key Features

Watch Functions

Replace Builders with simple one-line watch calls:

  • watchValue — Watch ValueListenable properties from get_it objects

  • watchIt — Watch whole Listenable objects registered in get_it

  • watchPropertyValue — Watch specific property, rebuilds only when value changes

  • watchStream — Reactive streams without StreamBuilder

  • watchFuture — Reactive futures without FutureBuilder

  • watch — Watch any local Listenable

Handler Functions (Side Effects)

Execute side effects without rebuilding:

Watching objects created by cached factories with parameters

If you have one manager per entity (e.g. per station id), register it with registerCachedFactoryParam and pass the parameter to the watch function. When the parameter changes, watch_it automatically unsubscribes from the old instance and subscribes to the new one:

di.registerCachedFactoryParam<StationManager, String, void>(
  (stationId, _) => StationManager(stationId),
);

class StationTile extends WatchingWidget {
  final String stationId;
  const StationTile({super.key, required this.stationId});

  @override
  Widget build(BuildContext context) {
    final name = watchValue((StationManager m) => m.name, param1: stationId);
    return Text(name);
  }
}

param1/param2 are available on all watch and handler functions that resolve their object from get_it. They are only valid for types registered with registerCachedFactoryParam. Plain registerFactory registrations can't be watched at all (every build would get a new instance) and are rejected in debug mode.

Lifecycle Helpers

Powerful functions for StatelessWidgets:

  • createOnce — Create objects on first build, auto-dispose on widget destroy

  • callOnce — Execute function only on first build

  • callOnceAfterThisBuild — Execute function once after current build completes

  • callAfterEveryBuild — Execute function after every rebuild

  • pushScope — Automatic get_it scope management tied to widget lifecycle

Important Rules ⚠️

All watch* calls must:

  • Be called inside build() method
  • Be called in same order every build
  • Not be conditional (no if wrapping watch calls)

Why these rules? watch_it uses index-based retrieval similar to React Hooks. Changing the order breaks the mapping between calls and stored data.

Read the detailed explanation →

Widget Types

Choose the widget type that fits your needs:

  • WatchingWidget — Extends StatelessWidget, use for simple widgets
  • WatchingStatefulWidget — Extends StatefulWidget, use when you need lifecycle or local state
  • WatchItMixin — Add to existing StatelessWidget with with WatchItMixin
  • WatchItStatefulWidgetMixin — Add to existing StatefulWidget with with WatchItStatefulWidgetMixin

Learn which to use when →

Ecosystem Integration

Built on get_it — watch_it is designed to work with get_it's service locator pattern. Register your models, services, and business logic with get_it, then watch them reactively.

// Register with get_it
di.registerLazySingleton(() => UserManager());
di.registerLazySingleton(() => TodoManager());

// Watch them in any widget
class MyWidget extends WatchingWidget {
  @override
  Widget build(BuildContext context) {
    final user = watchIt<UserManager>();
    final todos = watchValue((TodoManager m) => m.todos);
    return ListView(...);
  }
}

Want more? Combine with other flutter_it packages:

  • get_it — Recommended pairing. Service locator for dependency injection. Access global services with di<T>().

  • Optional: command_it — Command pattern with loading/error states. Watch Commands reactively for automatic UI updates.

  • Optional: listen_it — ValueListenable operators (map, debounce, where). Watch reactive collections (ListNotifier, MapNotifier, SetNotifier).

💡 flutter_it is a construction set — watch_it + get_it is the recommended foundation. Add command_it and listen_it when you need advanced features. Each package works independently.

Explore the ecosystem →

AI-Assisted Development

This package ships an Agent Skill for AI coding assistants (Claude Code, Cursor, GitHub Copilot, Codex, Gemini CLI and others) in skills/watch-it-expert/. It teaches them the critical rules, common patterns and anti-patterns of watch_it. Install it into your project with the official Dart skills tool:

dart run skills@ get

dart run skills@ get only looks at direct dependencies. If you use get_it through watch_it, add get_it to your pubspec as well to also get get-it-expert.

For the ecosystem-wide skills (architecture guidance, feed/data-source patterns, overview) and the skills of the other flutter_it packages run:

dart run skills@ add flutter-it/flutter_it

Learn more about AI skills →

Learn More

📖 Documentation
💬 Community & Support

Contributing

Contributions are welcome! Please read the contributing guidelines before submitting PRs.

License

MIT License - see LICENSE file for details.


Part of the flutter_it ecosystem — Build reactive Flutter apps the easy way. No codegen, no boilerplate, just code.

카테고리

의존성

의존성 목록 2 개

소스 저장소

이 패키지를 사용하는 프로젝트