我对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
方法就会被调用.然而,日志(log)logger.e("Build CoachPosition");
一直被显示.正常吗?据我所知,它应该只调用一次.然后,当我按下"Start Session"
按钮时,值是0
.这个问题的解决方案是什么?