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

패키지 상세v0.3.0-beta

fountain

새로운 Flutter 패키지 프로젝트입니다.

AndroidiOSWebmacOSWindowsLinux
30일 다운로드
43
좋아요
9
Pub 점수
130

패키지 설치

flutter pub add fountain

패키지 개요

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

Fountain은 의존성 주입과 상태 관리를 위한 Flutter 패키지로, 애플리케이션 전반에서 종속성과 공유 상태를 깔끔하고 효율적으로 관리할 수 있는 방법을 제공합니다. 단순함을 중심으로 설계되어 개발자가 앱 라이프사이클 동안 서비스, 위젯 및 기타 컴포넌트를 쉽게 등록하고 가져올 수 있도록 합니다. Android, iOS, Web, macOS, Windows, Linux 등 모든 주요 플랫폼을 지원하여 크로스플랫폼 프로젝트에 이상적입니다. 최소한의 보일러플레이트와 직관적인 구문을 통해 개발 과정을 간소화하면서도 성능과 확장성을 유지합니다.

사용 사례

  • 크로스플랫폼 앱 개발
  • 공유 상태 관리
  • 대규모 앱에서의 의존성 주입
  • 서비스 등록 간소화
  • 모의 종속성으로 테스트하기

주요 기능

  • 최소한의 보일러플레이트
  • 플랫폼 독립적 설계
  • 간편한 서비스 등록
  • 내장형 라이프사이클 관리
  • 테스트용 모킹 지원

적합한 대상

  • 경량 DI를 찾는 Flutter 개발자
  • 확장 가능한 상태 관리가 필요한 프로젝트
  • 테스트 가능성에 중점을 둔 팀
  • 다중 플랫폼을 대상으로 하는 앱
  • 복잡한 상태 솔루션을 피하는 개발자

고려 사항

  • 성숙한 대안에 비해 문서화가 제한적
  • 작은 커뮤니티 규모
  • 새 사용자에게는 학습 곡선이 필요할 수 있습니다
  • 매우 복잡한 상태 시나리오에는 적합하지 않음
  • 중간에서 대규모 애플리케이션에 가장 적합

원본 README

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

logo

The modular state management solution for flutter.

  • Easy debugging : each event is predictable and goes into a single pipeline
  • Centralized state : solid state validation
  • Power of async generators : writing asynchronous code is easy thanks to Dart generators

Quickstart

The global logical state of our application :

class CounterState {
  factory CounterState.initial() => const CounterState(0, 10);
  const CounterState(this.count, this.max);
  final int count;
  final int max;
  bool get isMax => count >= max;
}

The available actions that alterate the logical state of the application :

class AddAction extends Action<CounterState> {
  const AddAction(this.value);
  final int value;
  @override
  Stream<Updater<CounterState>> call(
    Context<CounterState> context,
  ) async* {
    yield (state) => CounterState(min(state.count + value, state.max), state.max);
  }
}

class ResetAction extends Action<CounterState> {
  @override
  Stream<Updater<CounterState>> call(
    Context<CounterState> context,
  ) async* {
    yield (state) => CounterState(0, state.max);
  }
}

class SaveAction extends Action<CounterState> {
  @override
  Stream<Updater<CounterState>> call(
    Context<CounterState> context,
  ) async* {
    await File(_cachePath).writeAsString(context.state.count.toString());
  }
}

class LoadAction extends Action<CounterState> {
  @override
  Stream<Updater<CounterState>> call(
    Context<CounterState> context,
  ) async* {
    final content = await File(_cachePath).readAsString();
    final count = int.parse(content);
    yield (state) => CounterState(min(count, state.max), state.max);
  }
}

The view that subscribes to the state changes and dispatches actions :

class MyHomePage extends StatelessWidget {
  MyHomePage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Demo Home Page'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Builder(
              builder: (context) {
                /// This widget will be rebuilt each time the `count` value changes
                final count =
                    context.select((CounterState state) => state.count);
                return Text(
                  '$count',
                  style: Theme.of(context).textTheme.headline4,
                );
              },
            ),
          ],
        ),
      ),
      floatingActionButton: Builder(
        builder: (context) {
          /// This widget will be rebuilt each time the `isMax` value changes
          final isMax = context.select((CounterState state) => state.isMax);
          if (isMax) {
            return FloatingActionButton(
              /// The action is executed in the [ApplicationContext].
              onPressed: () => context.dispatch<CounterState>(ResetAction()),
              tooltip: 'Reset',
              child: Icon(Icons.delete),
            );
          }

          return FloatingActionButton(
            /// The action is executed in the [ApplicationContext].
            onPressed: () => context.dispatch<CounterState>(AddAction(1)),
            tooltip: 'Increment',
            child: Icon(Icons.add),
          );
        },
      ),
    );
  }
}

The state initialization at the root of the tree with the Fountain widget :

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Fountain(
      initialState: (context) => CounterState.initial(),
      child: MaterialApp(
        title: 'Flutter Demo',
        theme: ThemeData(
          primarySwatch: Colors.blue,
        ),
        home: MyHomePage(),
      ),
    );
  }
}

Core concepts

schema

Context

The application context maintains a unique global logical immutable state for the application.

The context also contains all the middlewares that will process the dispatched event.

The application context is provided to the widget tree from a Fountain so that any descendent widget can observe a property of the state with the select extension method. It can also dispatch events into the middlewares with the dispatch extension methods.

Middleware

The application middleware process the dispatched Events and can produce state updates.

They are composable by nature which means that each middleware can wrap another middleware.

Event

The events are inputs for middlewares. They can describe a user action, or a system event for exemple. They are processed by the middlewares which can produce new application states.

Included middlewares

To import middlewares, use the import 'package:fountain/middlewares.dart'; directive.

Actions

By default, the framework includes a ActionExecutor<TState> middleware that allows to define Action<TState>s which are then invoked directly to produce new states.

Defining an action

To create custom actions, inherits from Action<TState> and implement all of the update logic in the call method. Since the method returns a Stream, a convenient way to implement the logic is often by using async * generators which allows to yield a sequence of state updates.

class RefreshAction extends Action<MyApp> {
  const RefreshAction();

  @override
  Stream<Updater<CounterState>> call(
    Context<CounterState> context,
  ) async* {
    if(!context.state.isLoading) {
        yield (state) => state.copyWith(
            isLoading: true,
        );

        final news = await Api.instance.getNews();

        yield (state) => state.copyWith(
            isLoading: false,
            news: news,
        );
    }
  }
}

Note that the actions aren't yielding states directly, but Updaters. This is to insist on the fact the the initial state may have changed during the action execution, and therefore, it must be taken into account when updated.

Logging

The framework also includes a Logging middleware that logs all events and state updates.

Fountain(
    middlewares: <Middleware<CounterState>>[
        Logging<CounterState>(),
        ...Fountain.defaultMiddlewares<CounterState>(),
    ],
    // ...
);
ErrorHandler

This middleware catches all unmanaged exceptions from middlewares below it and dispatches new events if so.

Fountain(
    middlewares: <Middleware<CounterState>>[
        ErrorHandler<CounterState>(
            (context, event, initialState,error,stackTrace) {
                // An unknow error occured during event processing
                return DisplayAlertAction('Sorry, an error occured');
            },
        ),
        ...Fountain.defaultMiddlewares<CounterState>(),
    ],
    // ...
);

About

Wait ... yet another state management solution for Flutter ?

Fountain is not so new to me, I've used this approach for a longtime now. Centralizing it as an opensource library makes a lot of sense to create a standard for a all of my personal and professional projects.

Inspired by

This project stands on the shoulders of giants, with the intention of reducing boilerplate, being minimalist and simple at its core.

  • Redux for the functional update cycle and general principles, with the purpose of having less boilerplate by being a bit more opiniated.
  • Express | Koa for their composability and modularity thanks to middlewares.
  • Bloc for its use of Streams.
  • Provider for its select method.
How is it different from other popular solutions ?
  • Provider : Fountain is more opiniated than Provider, and thus Provider is a more general purpose tool. Provider is often used in combination with a ChangeNotifier to create a simple state management solution.
  • Redux : Fountain has the same overall philosophy than Redux with Thunks but brings less boilerplate when dealing with asynchronous logic with ApplicationActions logic by using Streams. Fountain also brings the middleware concepts.
  • Bloc : Fountain use a global state instead of various Blocs. We believe it is important since there's a lot of areas which need to be aware of another part of your app logic. This makes also persistence, testability easier to deal with.

카테고리

의존성

의존성 목록 2 개

소스 저장소

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

아직 데이터가 없습니다.