我对 Riverpod
比较陌生,因此我在使用 NotifierProvider
时遇到了一个奇怪的问题。这是我的通知程序:
@riverpod
class CoachPosition extends _$CoachPosition {
@override
int build() {
logger.e("Build CoachPosition");
return 0;
}
void updatePosition(int position) {
state = position;
}
}
这是我的小部件,用于获取并显示教练列表(工作正常)。我有大约 5 名教练。
final coachesWidget = ref.watch(fetchCoachPreviewsProvider).when(
data: (List<CoachPreview> list) {
return CarouselSlider.builder(
itemCount: list.length,
itemBuilder: (BuildContext context, int itemIndex, int pageViewIndex) => _FlipCard(list[itemIndex]),
options: CarouselOptions(
height: double.infinity,
enlargeCenterPage: true,
enlargeFactor: 0.2,
onPageChanged: (index, reason) {
logger.e("onPageChanged: $index");
ref.read(coachPositionProvider.notifier).updatePosition(index);
},
),
);
},
error: (Object error, StackTrace stackTrace) {
return const Center(
child: Icon(Icons.error),
);
},
loading: () {
return const Center(
child: CircularProgressIndicator(),
);
},
);
这是我检查教练位置的按钮:
SizedBox(
height: 48,
child: ElevatedButton(
onPressed: () {
final index = ref.read(coachPositionProvider);
logger.e("start session with coach index: $index");
},
style: ElevatedButton.styleFrom(
backgroundColor: Colors.white,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(25),
),
elevation: 4.0,
),
child: const Text("Start Session", style: TextStyle(fontSize: 19, color: Colors.black54)),
),
),
问题是每当我更改 CarouselSlider
时,索引就会更改并且调用 updatePosition
方法。但是,日志 logger.e("Build CoachPosition");
始终显示。正常吗?据我了解,它应该只被调用一次。然后,当我按下“Start Session”
按钮时,该值为0
。问题的解决方案是什么?
最佳答案
如果您的coachPositionProvider
当前未被其他提供商|小部件监听,则每次都会重新创建它。要更改此行为,请开始永久监听(例如,尝试使用 ref.listen
),或者将 keepAlive
参数添加到注释中:
@Riverpod(keepAlive: true)
class CoachPosition extends _$CoachPosition {...}
关于flutter - NotifierProvider 每次更新都会重新构建并且值不更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76797374/