我有一个这样的模型:
class TimerModel {
const TimerModel(this.timeLeft, this.buttonState);
final String timeLeft;
final ButtonState buttonState;
}
enum ButtonState {
initial,
started,
paused,
finished,
}
这是StateNotifierProvider:
class TimerNotifier extends StateNotifier<TimerModel> {
TimerNotifier() : super(_initialState);
static const int _initialDuration = 10;
static final _initialState = TimerModel(
_durationString(_initialDuration),
ButtonState.initial,
);
final Ticker _ticker = Ticker();
StreamSubscription<int> _tickerSubscription;
void start() {
if (state.buttonState == ButtonState.paused) {
_tickerSubscription?.resume();
state = TimerModel(state.timeLeft, ButtonState.started);
} else {
_tickerSubscription?.cancel();
_tickerSubscription =
_ticker.tick(ticks: _initialDuration).listen((duration) {
state = TimerModel(_durationString(duration), ButtonState.started);
});
_tickerSubscription.onDone(() {
state = TimerModel(state.timeLeft, ButtonState.finished);
});
state =
TimerModel(_durationString(_initialDuration), ButtonState.started);
}
}
static String _durationString(int duration) {
final String minutesStr =
((duration / 60) % 60).floor().toString().padLeft(2, '0');
final String secondsStr =
(duration % 60).floor().toString().padLeft(2, '0');
return '$minutesStr:$secondsStr';
}
void pause() {
_tickerSubscription?.pause();
state = TimerModel(state.timeLeft, ButtonState.paused);
}
void reset() {
_tickerSubscription?.cancel();
state = _initialState;
}
@override
void dispose() {
_tickerSubscription?.cancel();
super.dispose();
}
}
class Ticker {
Stream<int> tick({int ticks}) {
return Stream.periodic(Duration(seconds: 1), (x) => ticks - x - 1)
.take(ticks);
}
}
我可以像这样监听状态的所有变化:
final timerProvider = StateNotifierProvider<TimerNotifier>((ref) => TimerNotifier());
但是,我想让另一个提供程序仅侦听ButtonState中的更改。这不起作用:
final buttonProvider = StateProvider<ButtonState>((ref) {
return ref.watch(timerProvider.state).buttonState;
});
因为它仍然返回所有状态更改。
这也不起作用:
final buttonProvider = StateProvider<ButtonState>((ref) {
return ref.watch(timerProvider.state.buttonState);
});
因为state
对象没有buttonState
属性。
我如何只观看buttonState的更改?
答案 0 :(得分:0)
每当监视状态更改时,使用watch
都会给出一个新状态。这样可以分两部分解决问题:
final _buttonState = Provider<ButtonState>((ref) {
return ref.watch(timerProvider.state).buttonState;
});
每次timerProvider.state
更改时,使用此提供程序都将导致重建。但是,技巧是执行以下操作:
final buttonProvider = Provider<ButtonState>((ref) {
return ref.watch(_buttonState);
});
由于_buttonState
对于大多数timerProvider.state
的更改都是相同的,因此观看_buttonState
仅在_buttonState
实际更改时才会引起重建。
感谢this post显示答案。该帖子还表明不久将有一个简化的语法:
final buttonState = ref.watch(timerProvider.state.select((state) => state.buttonState));