You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter使用flutter_bloc包时如何将现有Repository实例传递到下一页

RepositoryProvider 同样提供了 .value 命名构造方法,支持直接传入已创建完成的 repository 实例,不需要通过 create 方法新建,和你用到的 BlocProvider.value 用法完全一致。

你可以按照如下代码修改路由跳转逻辑:

Navigator.of(context).push(
  MaterialPageRoute<CreateFeedSelectClass>(
    builder: (_) => RepositoryProvider.value(
      // 直接传入当前页面已经初始化好的实例即可
      value: _teacherRepository,
      child: CreateFeedSelectClass(
        imageStringList: state.selectedImages,
        imagePathList: state.selectedImagePaths,
        classList: state.classList,
      ),
    ),
  ),
);

后续在新页面中,你可以通过 RepositoryProvider.of<TeacherRepository>(context) 正常获取到这个实例。

注意事项:

  • 以 .value 方式传入的实例,RepositoryProvider 不会自动管理它的销毁逻辑,你需要在持有该实例的页面自行管理生命周期,和 BlocProvider.value 的生命周期逻辑保持一致。

内容的提问来源于stack exchange,提问作者Manas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 21:48:01