パッケージ、リポジトリ、アプリカテゴリを検索

パッケージ詳細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 を使用します
  • DI用の組み込みサービスロケーター
  • 最小限のボイラープレート
  • 状態変更時にウィジェットの再構築が自動で行われる
  • 洗練された、読みやすい 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.

カテゴリー

ソースリポジトリ

このパッケージを使用しているプロジェクト

データはまだありません。