모델의 전체 개체가 아닌 특정 속성만 관찰함으로써 세밀한 상태 업데이트를 허용하는 경량 플러터 패키지입니다. 대상 속성이 변경될 때만 리스너에 알림을 보내므로 UI 컴포넌트에서 불필요한 재생성 횟수를 줄입니다. 복잡한 모델과 자주 업데이트되는 앱의 성능 최적화에 이상적입니다. 기존의 ChangeNotifier 워크플로와 원활하게 통합되며 모든 주요 플랫폼을 지원합니다.
사용 사례
대규모 상태 보유 위젯에서 UI 성능 최적화
모델의 일부만 변경될 때 불필요한 재빌드를 줄이는 것
복잡한 데이터 모델에서 부분 상태 업데이트 관리
여러 필드를 가진 폼에서 반응성 향상
리스너 알림에 대한 세밀한 제어 활성화
주요 기능
관찰자 전용 속성
최소한의 보일러플레이트
ChangeNotifier와의 원활한 통합
모든 플러터 플랫폼을 지원합니다
속성 변경을 기반으로 한 효율적인 재구성
경량이며 도입하기 쉬움
적합한 대상
세밀한 상태 관리를 원하는 개발자
부분 업데이트가 필요한 복잡한 모델을 가진 앱
성능에 민감한 애플리케이션
ChangeNotifier를 이미 사용하는 팀
위젯 재구성 횟수를 줄이려는 프로젝트
고려 사항
관찰할 속성을 정확히 추적해야 한다
전체 모델 변경 시나리오에 적합하지 않습니다
속성 수준 알림에 한정
간단한 사용 사례에 대해 복잡성을 증가시킬 수 있음
관심사의 분리가 명확할 때 가장 잘 사용됩니다
원본 README
연결된 소스 저장소의 README 원문 스냅샷입니다. 최신 내용은 저장소에서 확인하세요.
property_change_notifier
A drop-in replacement for ChangeNotifier for observing only certain properties of a model.
Why?
ChangeNotifier is useful for observing changes to a model. The problem is that it takes an all-or-none approach. There is no way to listen only to specific properties. To do so requires every property to be implemented as a ValueNotifier or similar. The Observable package has some powerful tools but they are not backwards-compatible with ChangeNotifier.
PropertyChangeNotifier is an implementation of a more granular observer pattern similar to PropertyChangeListener in Java and INotifyPropertyChanged in .NET. When a property changes, the name of the property is included in the notification. Listeners can then choose to observe only one or many properties.
How?
PropertyChangeNotifier works by extending ChangeNotifier in a way that makes it 100% backwards compatible with existing code.
Replace ChangeNotifier with PropertyChangeNotifier in your model.
Update your model to include the property name when calling notifyListeners().
When ready, update existing listeners to observe only specific properties.
You can use PropertyChangeNotifier as a superclass or a mixin. Just indicate the generic type of the property you provide to notifyListeners(). This is typically a String but can be any type.
Listening to a single property
Provide an additional parameter containing the property name you wish to observe, wrapped in an Iterable (typically a List):
final model = MyModel();
model.addListener(_listener, ['foo']);
void_listener() {
print('foo was changed');
}
Listening to multiple properties
Provide a Iterable containing the property names you wish to observe. The listener will be invoked when any of the given properties change. If the listener accepts a property parameter, it will be provided the name of the property that changed.
final model = MyModel();
model.addListener(_listener, ['foo', 'bar']);
void_listener(String property) {
print('$property was changed');
}
Listening to all properties
This is the default behavior of ChangeNotifier and remains the same, even if you've update your model to invoke notifyListeners() with a property name. If the listener accepts a property parameter, it will be provided the name of the property that changed.
final model = MyModel();
model.addListener(_listenerOne);
model.addListener(_listenerTwo);
void_listenerOne() {
print('model was changed');
}
void_listenerTwo(String property) {
print('$property was changed');
}
Adding listeners
Listeners can be added at any time. Adding a listener with no parameters will cause it to listen to all properties. The same listener can be added to multiple properties. Adding the same listener again is a no-op. It doesn't hurt to add a listener to a non-existent property, but it serves no purpose; PropertyChangeNotifier has no way of knowing if the property actually exists.
final model = MyModel();
model.addListener(_fooListener, ['foo']);
model.addListener(_bothListener, ['foo', 'bar']);
model.addListener(_allListener);
// _fooListener is listening to foo only.// _bothListener is listening to foo and bar only.// _allListener is listening to all properties.
Removing listeners
Listeners can be removed at any time. A listener can be removed from one or more properties without being removed from other properties. Removing a listener that does not exist is a no-op.
final model = MyModel();
model.addListener(_listener, ['foo', 'bar', 'baz']);
model.removeListener(_listener, ['bar', 'baz']);
// _listener is now listening to foo only.
String constants as property names
Referring to properties using string literals is error-prone and leads to stringly-typed code. To avoid this, you can reference string constants in both your model and listeners so that they can be safely checked by the compiler:
It might be more convenient to use enum values for property names. Remember to pass the property type as a generic argument to the PropertyChangeNotifier declaration.
You can even use your own custom types as property names. They just must extend Object and correctly implement equality using == and hashCode.
Usage with Widgets
PropertyChangeProvider can be used to expose a PropertyChangeNotifier instance to descendant widgets, and optionally rebuild them when all or certain properties change. First, create a root PropertyChangeProvider widget with an instance of your model. Be sure to provide the two generic type parameters: the first being your model type and the second, your property type:
Then, from any descendant widget, listen for changes to all or some properties by using the standard of() syntax typically used with InheritedWidget. You can then access either the model itself or its last changed property. Again, remember to provide the same two generic type parameters. Here are a few different examples:
Rebuilding when any property changes
Just call the static of() method anywhere from your widget, passing in its BuildContext.
Provide a properties parameter list with multiple values.
@override
Widget build(BuildContext context) {
PropertyChangeProvider.of<MyModel, String>(context, properties: ['foo', 'bar']);
return Text('Foo or Bar changed!);
}
Accessing the model instance
Call value on the return value of the of() method.
@overrideWidgetbuild(BuildContext context) {
final model = PropertyChangeProvider.of<MyModel, String>(context).value;
...
}
Accessing the model instance without rebuilding
You may want to just access the model without registering for a rebuild. For example, a button that mutates the model does not need to listen for changes. Provide a listen parameter with a value of false:
@overrideWidgetbuild(BuildContext context) {
final model = PropertyChangeProvider.of<MyModel, String>(context, listen: false).value;
...
}
Accessing the changed properties
Useful if you are listening to all or multiple properties and wish to know which ones were changed in the current build frame. Call properties on the return value of the of() method.
@overrideWidgetbuild(BuildContext context) {
final properties = PropertyChangeProvider.of<MyModel, String>(context).properties;
...
}
Accessing as a widget
PropertyChangeConsumer is a widget-based listener for cases where a BuildContext is hard to access, or if you prefer this kind of API. You can access both the model value and the changed properties via the builder callback. Again, remember to provide both generic type parameters:
If you have multiple PropertyChangeProvider widgets you wish to expose at the root of your tree, you can use the MultiPropertyChangeProvider to avoid nesting:
Thanks to the new type alias feature avaiable as of Dart 2.13, this package comes with several less verbose alternatives to use in the common use case where property names are of type String.