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

패키지 상세v4.2.2

get_it_mixin

GetIt에 저장된 객체와 위젯을 바인딩하는 것을 더 쉽게 만드는 Stateless 및 Stateful 위젯용 믹스인입니다.

AndroidiOSWebmacOSWindowsLinux
30일 다운로드
2.9천
좋아요
141
Pub 점수
130

패키지 설치

flutter pub add get_it_mixin

패키지 개요

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

get_it_mixin 패키지는 인기 있는 의존성 주입 라이브러리인 GetIt에 등록된 종속성을 쉽게 바인딩할 수 있도록 Stateless 및 Stateful 위젯을 위한 편리한 믹스인을 제공합니다. GetItMixin을 혼합함으로써 위젯은 build 메서드 내에서 직접 주입된 서비스, 저장소 또는 기타 객체에 접근할 수 있으며, 수동으로 가져오지 않아도 됩니다. 이는 반복적인 코드를 줄이고 특히 의존성 관리가 중요한 대규모 Flutter 애플리케이션에서 가독성을 향상시킵니다. 이 믹스인은 GetIt의 API와 원활하게 통합되며 모든 주요 플랫폼을 지원합니다.

사용 사례

  • 위젯 내 종속성 접근 간소화
  • GetIt 사용 시 반복 코드 줄이기
  • UI 계층에서 관심사의 명확한 분리를 가능하게 하기
  • 주입된 서비스를 통한 상태 관리 간소화
  • 구체적인 구현에서 위젯 로직을 분리함으로써 테스트 가능성을 향상시키기

주요 기능

  • GetIt과의 간편한 통합
  • 반복적인 종속성 검색을 줄입니다
  • 상태가 없는 위젯과 상태가 있는 위젯 모두를 지원합니다
  • 최소 코드 오버헤드
  • 모든 플러터 플랫폼에서 작동합니다

적합한 대상

  • 의존성 주입을 위해 GetIt을 사용하는 개발자
  • 위젯 뼈대 코드를 줄이려는 프로젝트
  • 유지보수 가능한 UI 코드를 우선시하는 팀
  • 복잡한 종속성 트리가 있는 Flutter 앱
  • UI와 비즈니스 로직 간의 명확한 분리를 요구하는 응용 프로그램

고려 사항

  • 먼저 GetIt를 설정해야 합니다
  • 과도하게 사용할 경우 복잡성이 증가할 수 있습니다
  • 의존성이 적은 간단한 앱에는 필요하지 않음
  • 적절한 종속성 등록과 함께 사용할 때 가장 효과적입니다
  • GetIt 기반 DI 워크플로우에 한정

원본 README

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

Hi my friends,

I recently published my new package watch_it https://github.com/escamoteur/watch_it, an overhauled version of the get_it_mixin but with a more intuitive and streamlined API. Porting an existing project using get_it_mixin is really easy and quick.

To better connect with my package users I know opened a Discord Server to support my packages https://discord.gg/ZHYHYCM38h

This package here won't be further maintained. You can continue using the latest version but I won't add new features or fix bugs.

get_it_mixin

A set of mixins that allow widgets to watch data registered with GetIt. Widgets that watch data will rebuild automatically whenever that data changes.

Supported data types that can be watched are ChangeNotifier, ValueNotifier, Stream and Future.

ChangeNotifier based example:

// Create a ChangeNotifier based model
class UserModel extends ChangeNotifier {
  get name = _name;
  String _name = '';
  set name(String value){
    _name = value;
    notifyListeners();
  }
  ...
}

// Register it 
getIt.registerSingleton<UserModel>(UserModel());

// Watch it
class UserNameText extends StatelessWidget with GetItMixin {
  @override
  Widget build(BuildContext context) {
    final userName = watchOnly((UserModel m) => m.name);
    return Text(userName);
  }
}

Reading Data

Reading data is already quite easy with GetIt, but it gets even easier with the mixin. Just add a GetItMixin to a StatelessWidget and call get<T>:

class MyWidget extends StatelessWidget with GetItMixin {
  void _handleSubmitPressed() {
    final email = get<Model>().emailAddress;
    ...
  }
}

You can do the same thing on StatefulWidget using a GetItStatefulWidgetMixin and GetItStateMixin:

class MyWidget extends StatefulWidget with GetItStatefulWidgetMixin {
  _MyWidgetState createState() => _MyWidgetState();
}
class _MyWidgetState extends State<MyWidget> with GetItStateMixin {
  void _handleSubmitPressed() {
    final email = get<Model>().emailAddress;
    ...
  }
}

NOTE: The GetItMixin API is generally the same regardless of whether you use Stateless or Stateful widgets.

Watching Data

Where GetItMixin really shines is data-binding. It comes with a set of watch methods to rebuild a widget when data changes.

Imagine you had a very simple shared model, with multiple fields, one of them being country:

class Model {
    final country = ValueNotifier<String>('Canada');
    ...
}
getIt.registerSingleton<Model>(Model());

You could tell your view to rebuild any time country changes with a simple call to watchX:

class MyWidget extends StatelessWidget with GetItStatefulWidgetMixin {
  @override
  Widget build(BuildContext context) {
    String country = watchX((Model x) => x.country);
    ...
  }
}

There are various watch methods, for common types of data sources, including ChangeNotifier, ValueNotifier, Stream and Future:

API Description
.watch Bind to a ValueListenable value
.watchX Bind to the results of a select method on a ValueListenable value
.watchOnly Bind to a basic Listenable (like ChangeNotifier)
.watchXOnly Bind to the results of a select method on a Listenable
.watchStream Subscribe to a Stream
.watchFuture Bind to a Future

Just call watch_ to listen to the data type you need, and GetItMixin will take care of cancelling bindings and subscriptions when the widget is destroyed.

The primary benefit to the watch methods is that they eliminate the need for ValueListenableBuilders, StreamBuilder etc. Each binding consumes only one line and there is no nesting.

Here we watch three ValueListenable which would normally be three builders, 12+ lines of code and several levels of indentation. With GetItMixin, it's three lines:

class MyWidget extends StatelessWidget with GetItMixin {
  @override
  Widget build(BuildContext context) {
    bool loggedIn = watchXOnly((UserModel x) => x.isLoggedIn);
    String userName = watchXOnly((UserModel x) => x.user.name);
    bool darkMode = watchXOnly((SettingsModel x) => x.darkMode);
    ...
  }
}

This can be used to eliminate StreamBuilder and FutureBuilder from your UI as well:

class MyWidget extends StatelessWidget with GetItMixin {
  @override
  Widget build(BuildContext context) {
    final currentUser = watchStream((UserModel x) => x.userNameUpdates, 'NoUser');
    final ready = watchFuture((AppModel x) => x.initializationReady, false).data;
    bool appIsLoading = ready == false || currentUser.hasData == false;
    
    if(appIsLoading) return CircularProgressIndicator();
    return Text(currentUser.data);    
  }
}
Side Effects / Event Handlers

Instead of rebuilding, you might instead want to show a toast notification or dialog when a Stream emits a value or a ValueListenable changes.

To run an action when data changes you can use the register methods:

API Description
.registerHandler Add an event handler for a ValueListenable
.registerStreamHandler Add an event handler for a Stream
.registerFutureHandler Add an event handler for a Future

The first param in the register methods is a select delegate that can be used to watch a specific field. The second param is the action which will be triggered when that field changes:

class MyWidget extends StatelessWidget with GetItMixin {
  @override
  Widget build(BuildContext context) {
    registerHandler(
        (Model x) => x.name,
        (context, value, cancel) => showNameDialog(context, value));
    ...
  }
}

In the example above you see that the handler function receives the value that is returned from the select delegate ((Model x) => x.name), as well as a cancel function that the handler can call to cancel registration at any time.

As with watch calls, all registerHandler calls are cleaned up when the Widget is destroyed.

Rules

There are some important rules to follow in order to avoid bugs with the watch methods:

  • watch methods must be called within build()
    • It is good practice to define them at the top of your build method
  • must be called on every build, in the same order (no conditional watching). This is similar to flutter_hooks.
  • do not use them inside of a builder as it will break the mixins ability to rebuild

isReady() and allReady()

A common use case is to toggle a loading state when side effects are in-progress. To check whether any registered actions have completed you can use allReady() and isReady<T>(). These methods return the current state of any registered async operations and a rebuild is triggered when they change.

class MyWidget extends StatelessWidget with GetItMixin {
  @override
  Widget build(BuildContext context) {
    allReady(onReady: (context)
      => Navigator.of(context).pushReplacement(MainPageRoute()));
    return CircularProgressIndicator();
  }
}

Check out the GetIt docs for more information on the isReady and allReady functionality: https://pub.dev/packages/get_it

Pushing a new GetIt Scope

With pushScope() you can push a scope when a Widget/State is mounted, and automatically pop when the Widget/State is destroyed. You can pass an optional init or dispose function.

  void pushScope({void Function(GetIt getIt) init, void Function() dispose});

This can be very useful for injecting mock services when views are opened so you can easily test them. Of course you can also push and pop scope directly from your tests as well!

Find out more!

For more background on the history of GetItMixin you can check out the README_EXTENDED.

For a more complete explanation of the API watch the presentation: GetIt in action By Thomas Burkhart.

카테고리

의존성

의존성 목록 2 개

  • functional_listener^2.1.0
  • get_it^7.6.0

소스 저장소

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