搜尋套件、儲存庫與 APP 分類

套件詳情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 狀態管理解決方案,它利用 get_it 服務定位器來觀察已註冊物件的變更,並在這些變更發生時自動重繪 UI。透過與 get_it 無縫整合,它簡化了狀態更新,無需複雜的樣板程式碼或額外的小部件。對於需要與服務物件綁定的反應式行為之應用程式來說,Watch 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 項

原始碼儲存庫

使用此套件的專案