3异步_响应式_状态管理

状态管理

graph LR
StateMangement-->BLOC/Stream+StreamBuilder/Rxdart
StateMangement-->Redux
StateMangement-->Provider/ScopedModel

rxdart

https://pub.dev/packages/rxdart

Dart RxDart
Stream Observable
StreamController Subject

redux

Flutter Fish Redux架构演进2.0

https://pub.dev/packages/flutter_redux

https://pub.dev/packages/fish_redux

StroreProver和ChangeNotifierProvider是基于InheritedWidget,而BlocProvider不是

Provider基于context.getElementForInheritedWidgetOfExactType<_DefaultInheritedProviderScope>跨组件获取数据

而BlocProvider是基于: BlocProvider provider = context.ancestorWidgetOfExactType(type);跨组件获取数据

graph LR
subgraph redux
StoreProvider
StoreConnector
Store
end
StoreProvider-->|similar|ChangeNotifierProvider
StoreConnector-->|similar|Consumer
Store-->|similar|ChangeNotifier

subgraph provider
ChangeNotifierProvider
Consumer
ChangeNotifier
end

subgraph BLOC/Stream+StreamBuilder
ChangeNotifierProvider-->|similar|BlocProvider
ChangeNotifier-->|similar|XxxBloc
Consumer-->|similar|BlocProvider.of
end

state-mgmt

https://flutter.dev/docs/development/data-and-backend/state-mgmt

https://flutter.dev/docs/development/data-and-backend/state-mgmt/options

ephemeral state and app state

image

When asked about React’s setState versus Redux’s store, the author of Redux, Dan Abramov, replied:

“The rule of thumb is: Do whatever is less awkward.”

In summary, there are two conceptual types of state in any Flutter app. Ephemeral state can be implemented using State and setState(), and is often local to a single widget. The rest is your app state. Both types have their place in any Flutter app, and the split between the two depends on your own preference and the complexity of the app.

Simple app state management

On this page, we are going to be using the provider package. If you are new to Flutter and you don’t have a strong reason to choose another approach (Redux, Rx, hooks, etc.), this is probably the approach you should start with. ==The provider package== is easy to understand and it doesn’t use much code. It also uses concepts that are applicable in every other approach.

With provider, you don’t need to worry about callbacks or InheritedWidgets. But you do need to understand 3 concepts:

  • ChangeNotifier
  • ChangeNotifierProvider
  • Consumer

provider

https://pub.dev/packages/provider

https://pub.dev/documentation/provider/latest/

Consumer

Selector

参考

Future

https://api.dartlang.org/stable/2.0.0/dart-async/Future-class.html

setState+globalKey 实现按需build

setState重绘的核心有两个:

  • ==Model值的变更==
  • ==适当节点的rebuild替换==