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

Flutter Bloc中传递mealID参数实现API请求的问题求助

解决Bloc中传递mealID参数的方案

1. 重构FoodEvent为带参数的事件类

原枚举无法携带参数,需改为抽象类+具体事件子类的形式,让FetchFoodEvent承载mealID:

// bloc events
abstract class FoodEvent {}

class FetchCategoryEvent extends FoodEvent {}

class FetchFoodEvent extends FoodEvent {
  final String mealID;
  FetchFoodEvent(this.mealID);
}

2. 更新Bloc的事件处理逻辑

拆分事件处理方法,接收并使用FetchFoodEvent中的mealID参数:

// Main Bloc class 
class FoodBloc extends Bloc<FoodEvent, FoodState> {
  FoodRepository foodRepository = FoodRepository(authService: AuthService());

  FoodBloc() : super(InitialLoading()) {
    on<FetchCategoryEvent>(_onFetchCategory);
    on<FetchFoodEvent>(_onFetchFood);
  }

  Future<void> _onFetchCategory(FetchCategoryEvent event, Emitter<FoodState> emit,) async {
    emit(Loading());
    try {
      var categoryModel = await foodRepository.getCategory();
      emit(Success(categoryModel));
    } catch (e) {
      emit(Error(e.toString()));
    }
  }

  Future<void> _onFetchFood(FetchFoodEvent event, Emitter<FoodState> emit,) async {
    emit(Loading());
    try {
      var food = await foodRepository.getFood(event.mealID);
      emit(FoodSuccess(food));
    } catch (e) {
      emit(Error(e.toString()));
    }
  }
}

3. 在UI页面传递mealID到Bloc

修改DetailsScreen的事件添加逻辑,将页面接收的mealID传入事件:

// 初始化Bloc并展示数据的UI类
class DetailsScreen extends StatefulWidget {
  final String mealID;
  DetailsScreen({Key? key, required this.mealID}) : super(key: key);

  @override
  State<DetailsScreen> createState() => _DetailsScreenState();
}

class _DetailsScreenState extends State<DetailsScreen> {
  late FoodBloc foodBloc;

  @override
  void didChangeDependencies() {
    foodBloc = BlocProvider.of<FoodBloc>(context);
    foodBloc.add(FetchFoodEvent(widget.mealID));
    super.didChangeDependencies();
  }

  @override
  void dispose() {
    foodBloc.close();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container();
  }
}

注意事项

  • 事件类传参是Bloc官方推荐的灵活方案,支持多参数、复杂对象传递
  • 若Bloc为全局/上层BlocProvider提供,请勿在页面dispose中调用close(),避免影响其他页面使用

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 07:51:11