我对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.这个问题的解决方案是什么?

推荐答案

如果您的coachPositionProvider当前没有被其他Provider |小工具收听,则每次都会重新创建它.要更改此行为,请开始永久侦听它(例如,try 使用ref.listen),或将keepAlive参数添加到批注:

@Riverpod(keepAlive: true)
class CoachPosition extends _$CoachPosition {...}

Flutter相关问答推荐

当仅点击一行时,所有行都被选中

SingleChildScrollView正在将Container的高度限制为子对象,尽管使用了Expanded Inside Row()

我如何才能动态地将小部件排成一排进行排列呢?

Flutter 动画列表一次构建所有项目,而不是仅构建可见的项目

为什么要在值列表中两次放入空安全性

如何翻转这种剪刀设计

Flutter - Stripe:类型List 不是类型Map 的子类型? method_channel_stripe.dart 中的错误:263

如何使Flutter 边框宽度在外面而不是在里面?

在 Flutter 中解码 BLE 设备负载

在flutter中从图库或相机中 Select 图像的方法

用户文档 ID 与 Firestore 中的用户 ID 相同

PreferredSizeWidget类不能用作混合,因为它既不是混合类也不是混合

如何使这种相机叠加在Flutter 中?

Android Studio - Electric Eel 2022.1.1 更新 destruct 了 dart 文件图标

如何在 flutter 中使用 tabbar 作为底部导航栏?

如何显示从 MariaDB 获取的数据到列表视图

Show Snackbar above to showModalBottomSheet Flutter

如何使用列Flutter 中文本占用的空间来控制svg宽度

有没有办法帮助我修复类型 null 不是 Map 类型的子类型?

如何从dart 中的当前日期时间中减go 1 天?