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

套件詳情v2.1.0

inherited_state

基於 InheritedWidget 和依賴注入(DI)的簡單且乾淨的狀態管理,依賴於服務定位器模式。

AndroidiOSWebmacOSWindowsLinux
近 30 天下載
22
喜歡數
15
Pub 分數
150

安裝套件

flutter pub add inherited_state

套件介紹

根據套件公開資料產生的選型評估,僅供參考。

InheritedState 是一個輕量級的 Flutter 狀態管理解決方案,利用 InheritedWidget 實現高效元件樹更新,並採用服務定位器模式進行依賴注入。它提供乾淨、簡單的 API 來管理應用狀態,無需重複程式碼,非常適合中小型應用程式。該套件透過僅更新依賴於變更狀態的元件來確保最小重繪,同時也提供方便存取應用中共享服務的方式。專為想要獲得比更複雜狀態管理方案更直接替代方案的開發者設計。

適用情境

  • 簡單的應用狀態管理
  • Flutter 應用中的依賴注入
  • Provider 或 Riverpod 的輕量級替代方案
  • 在小部件樹之間管理共享資料
  • 減少有狀態小部件中的樣板程式碼

主要特色

  • 使用 InheritedWidget 來實現高效更新
  • 內建的服務定位器用於依賴注入
  • 最小化樣板程式碼
  • 狀態變更時自動重建成部件
  • 乾淨、易讀的 API
  • 支援所有主要平台

適合對象

  • 尋求簡潔的開發者
  • 中等狀態複雜度的專案
  • 希望快速設置的團隊
  • 需要依賴注入的應用程式
  • Flutter 初學者學習狀態管理

使用建議

  • 不太適合非常大型的應用
  • 與完整框架相比,進階功能有限
  • 需要理解 InheritedWidget
  • 可能需要額外的工具來進行測試
  • 比流行的替代方案少的社群支援

原始 README

以下為關聯原始碼儲存庫的 README 原文快照,最新內容請造訪原始碼儲存庫。

inherited_state

Simple scoped reactive state management (using [InheritedWidget]) and DI. Supports both immutable and mutable updates.

Quick Start

pubspec.yaml

inherited_state: ^2.1.0

Setup State Management

InheritedState widget needs to be part of the tree as an ancestor to be able to use it from the descendent widgets similar to the usage of InheritedWidget. You can register the reactive states using the states argument.

InheritedState(
    states: [
        Inject<Counter>(() => Counter(0)),
    ],
    builder: (_) =>
    ...
)
Reactive State - UI Change Notifications
// Plain dart class
class Counter {
    Counter(this.count);
    int count = 0;
}

// RS is an alias for ReactiveState.
void _incrementCounter() {
  // Immutable update
  final res = RS.set<Counter>(context, (counter) => Counter(counter.count + 1));
}

// Pass context to the `RS.get` method to subscribe to changes (widget automatically rebuilds when changes occur).
@override
Widget build(BuildContext context) {
    final counter = RS.get<Counter>(context);
    ...
}

Setup DI

void main() {
  registerDependencies();
  runApp(MyApp());
}

void registerDependencies() {
  SL.register(
    () => const AppConfig(
      appName: 'Inherited State Example',
      baseUrl: 'https://reqres.in/api',
    ),
  );
  SL.register(() => ApiService(SL.get()));
  SL.register(() => CounterService(SL.get()));
}
Service Locator (DI) - Services, Configs, etc.
// SL is an alias for ServiceLocator.
final counterService = SL.get<CounterService>();

Full Example with Reactive states and Services

main.yaml
import 'package:flutter/material.dart';
import 'package:inherited_state/inherited_state.dart';

import 'models/counter.dart';
import 'services/api_service.dart';
import 'services/app_config.dart';
import 'services/counter_service.dart';

void main() {
  registerDependencies();
  runApp(MyApp());
}

void registerDependencies() {
  SL.register(
    () => const AppConfig(
      appName: 'Inherited State Example',
      baseUrl: 'https://reqres.in/api',
    ),
  );
  SL.register(() => ApiService(SL.get()));
  SL.register(() => CounterService(SL.get()));
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return InheritedState(
        states: [
          Inject<Counter>(() => Counter(0)),
        ],
        builder: (_) {
          // final appConfig = InheritedService.get<AppConfig>();
          final appConfig = SL.get<AppConfig>();
          return MaterialApp(
            title: appConfig.appName,
            home: MyHomePage(title: appConfig.appName),
          );
        });
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final counterService = SL.get<CounterService>();
  Future<int> initialCounterFuture;

  @override
  void initState() {
    super.initState();
    initialCounterFuture = counterService.getInitialCounter();
    // Long form
    // initialCounterFuture.then((value) =>
    //     ReactiveService.getReactive<Counter>().setState((counter) => counter.count = value));
    // Short form - Mutatable update
    initialCounterFuture.then((value) =>
        RS.set<Counter>(context, (counter) => counter.count = value));
  }

  void _incrementCounter() {
    // Immutable update
    final res =
        RS.set<Counter>(context, (counter) => Counter(counter.count + 1));
    print('increment result: $res');
  }

  @override
  Widget build(BuildContext context) {
    final counter = RS.get<Counter>(context);
    print('rebuild: $counter');
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Text(
              'You have pushed the button this many times:',
            ),
            const SizedBox(height: 20),
            _buildFutureWaiter(
                (isReady) => Text(
                      '${counter.count}',
                      style: Theme.of(context).textTheme.headline4,
                    ),
                true),
          ],
        ),
      ),
      floatingActionButton: _buildFutureWaiter(
        (isReady) {
          print('floats $counter');
          return FloatingActionButton(
            backgroundColor: isReady ? null : Colors.grey,
            disabledElevation: 0,
            onPressed: isReady ? _incrementCounter : null,
            tooltip: 'Increment',
            child: const Icon(Icons.add),
          );
        },
      ),
    );
  }

  Widget _buildFutureWaiter(Widget Function(bool isReady) builder,
          [bool showSpinner = false]) =>
      FutureBuilder<int>(
        future: initialCounterFuture,
        builder: (_, snapshot) => showSpinner && !snapshot.hasData
            ? const CircularProgressIndicator()
            : builder(snapshot.hasData),
      );
}


View file

Inherited State Widget

This widget is used to setup the reactive state instances available to the descendants. It can be used multiple times at different tree nodes.

Reactive State

Reactive state allows for subscriptions and updates to the underlying model in an immutable and mutable fashion depending on developer preference.

Services

ServiceLocator allows for a simple way of registering global dependencies that can be used anywhere within the app without relying on flutter context or any sort of UI related mechanism. Services can be accessed and referenced and the reference is always a singleton.

所屬分類

原始碼儲存庫

使用此套件的專案

暫無相關資料。