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

패키지 상세v2.2.1

momentum

플러터용 MVC 패턴. 상태 관리, 종속성 주입 및 서비스 로케이터로 작동합니다.

AndroidiOSWebmacOSWindowsLinux
30일 다운로드
118
좋아요
97
Pub 점수
140

패키지 설치

flutter pub add momentum

패키지 개요

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

모멘텀은 모델-뷰-컨트롤러(MVC) 패턴을 구현하는 플러터 패키지로, 상태 관리, 종속성 주입 및 서비스 위치 지정을 위한 통합 솔루션을 제공합니다. 전용 모델, 뷰, 컨트롤러 계층을 통해 관심사의 분리를 통해 앱 아키텍처를 단순화하고 확장 가능하며 유지보수 가능한 코드를 가능하게 합니다. 모멘텀은 플러터 위젯 트리와 원활하게 통합되며, 안드로이드, iOS, 웹, 맥OS, 윈도우, 리눅스 등 모든 주요 플랫폼을 지원합니다. 가벼운 설계는 컴포넌트 간에 깔끔한 코드 구성과 효율적인 데이터 흐름을 촉진합니다.

사용 사례

  • 확장 가능한 Flutter 애플리케이션 빌드
  • 복잡한 앱 상태 관리
  • 의존성 주입 구현
  • 여러 상태 관리 솔루션 교체
  • 모듈화되고 테스트 가능한 코드 만들기

주요 기능

  • 내장된 MVC 아키텍처
  • 통합된 종속성 주입
  • 서비스 로케이터 기능
  • 크로스 플랫폼 지원
  • 최소한의 보일러플레이트
  • 자동 컨트롤러 생명주기 관리

적합한 대상

  • 구조화된 앱 아키텍처를 찾는 개발자
  • 상태 및 종속성 관리를 통합하고자 하는 팀
  • 유지보수 및 모듈식 코드가 필요한 프로젝트
  • 다중 플랫폼을 대상으로 하는 Flutter 앱
  • 다른 패턴보다 MVC를 선호하는 개발자

고려 사항

  • MVC에 익숙하지 않은 개발자를 위한 학습 곡선
  • 대안 대비 커뮤니티 채택률이 제한적
  • 기존 코드베이스를 리팩터링해야 할 수 있습니다
  • 중대규모 프로젝트에 가장 적합
  • 간단하거나 프로토타입 앱에는 적합하지 않음

원본 README

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

MVC pattern for flutter. Works as state management, dependency injection and service locator.

Pub Version Test GitHub stars GitHub license GitHub last commit


Model View Controller

Here's a diagram describing the flow between the state (model), widget (view) and the logic (controller):

Both MomentumController and MomentumModel are abstract classes that needs to be implemented. A pair of model and controller is called a component. MomentumBuilder is simply a widget. This is used to listen to controllers for rebuilds and accessing models to display their values.

Example

If you want to see a full code example that runs. Visit the example tab for more details or you can visit the official webpage. Otherwise, if you only want to see a glimpse of how momentum works, read the Overview and FAQs below.

Advance Example: Listify (clone the repo and run the app, requires Flutter 2.0.0)

Overview

MomentumModel - the data or state. Must be Immutable.

class ProfileModel extends MomentumModel<ProfileController> {
  // ...

  final int userId;
  final String username;

  // ...
}

MomentumBuilder - the view or widget to display the state.

MomentumBuilder(
  controllers: [ProfileController], /// injects both `ProfileController` and `ProfileModel`.
  builder: (context, snapshot) {
    var profileState = snapshot<ProfileModel>(); /// grab the `ProfileModel` using snapshot.
    var username = profileState.username;
    return // some widgets here ...
  }
)

MomentumController - the logic to manipulate the model or state.

class ProfileController extends MomentumController<ProfileModel> {
  // ...

  Future<void> loadProfile() async {
    var profile = await http.get(...);
    // update the model's properties.
    model.update(
      userId: profile.userId,
      username: profile.username,
    );
  }

  // ...
}

FAQs

How to rebuild the widget?

Calling model.update(...) from inside the controller rebuilds all the MomentumBuilders that are listening to it.


How to access the model object?

It is automatically provided by MomentumController for you to use. Inside a controller class, you can access it directly. It's never null.


How to initialize the model or state?

By implementing the T init() method which is required by MomentumController. Like this:

class ShopController extends MomentumController<ShopModel> {

  @override
  ShopModel init() {
    return ShopModel(
      this, // required
      shopList: [],
      productList: [],
    );
  }
}

Can I access the model properties inside my controller?

Of course. The model object is already provided by MomentumController meaning you can also directly access its properties like this:

class ShopController extends MomentumController<ShopModel> {

  bool hasProducts() {
    return model.productList.isNotEmpty;
  }
}

Is there a special setup required for Momentum to run?

Yes, definitely. This is the required setup for Momentum in a flutter app:

void main() {
  runApp(momentum());
}

Momentum momentum() {
  return Momentum(
    child: MyApp(),
    controllers: [
      ProfileController(),
      ShopController(),
    ],
    // and more optional parameters here.
  );
}

Testing

Momentum is highly testable. This is how a basic widget testing for momentum would look like:

void main() {

  testWidgets('should display username', (tester) async {
    var profileCtrl = ProfileController();

    await tester.pumpWidget(
      Momentum(
        child: MyApp(),
        controllers: [profileCtrl],
      ),
    );
    await tester.pumpAndSettle();

    profileCtrl.updateUsername("johndoe");
    await tester.pumpAndSettle(); // ensure rebuilds

    expect(profileCtrl.model.username, "johndoe"); // unit check
    expect(find.text("johndoe"), findsOneWidget); // widget check
  });
}

Or you might not be a fan of widget testing and only want to test your components:

void main() {

  test('should display username', () async {
    var profileCtrl = ProfileController();

    var tester = MomentumTester(
      Momentum(
        controllers: [profileCtrl],
      ),
    );
    await tester.init();

    profileCtrl.updateUsername("johndoe");
    expect(profileCtrl.model.username, "johndoe"); // unit check
  });
}

Other optional features

  • Routing - Navigation system that supports persistence. The app will open the page where the user left off.
  • Event System - For showing dialogs, prompts, navigation, alerts.
  • Persistence State - Restore state when the app opens again.
  • Testing - Tests your widgets and logic. Built-in helper class for unit testing.

Momentum leverages the power of setState(..) and StatefulWidget behind the scenes. The feature Event System uses Stream.

Router issues

  • The router doesn't support named routes yet.
  • The parameter handling for router is slightly verbose. And might be complicated for some. But it works magically.
  • Needs to explicitly implement RouterPage widget in order to handle the system's back button.
  • (FIXED ✅) The router breaks after hot reload. Only a problem during development but it should work in normal execution.

API Reference

Visit the official webpage of momentum to browse the full api reference, guides, and examples.


Thanks for checking out momentum. I hope you try it soon and don't hesitate to file on issue on github. I always check them everyday.

카테고리

의존성

의존성 목록 1 개

소스 저장소

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